PDF generated with PDFBox is blank

后端 未结 1 1836
执念已碎
执念已碎 2021-01-22 06:07

I am trying to write content into a PDF file. I have written the code

public ByteArrayOutputStream createPDF(String text) throws IOException, COSVisitor         


        
1条回答
  •  失恋的感觉
    2021-01-22 06:56

    You made two mistakes:

    1. You have closed the contentStream after saving the document instead of before.

    2. You haven't set a font.

    Code that works for me (exception handling removed):

    PDDocument document;
    PDPage page;
    PDPageContentStream contentStream;
    document = new PDDocument();
    
    page = new PDPage();
    document.addPage(page);
    contentStream = new PDPageContentStream(document, page);
    
    contentStream.setFont(PDType1Font.COURIER, 10);
    
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(100, 700);
    contentStream.drawString("Hello World Hello World Hello World Hello World Hello World");
    contentStream.endText();
    contentStream.close();
    document.save(....);
    document.close();
    

    0 讨论(0)
提交回复
热议问题