Add Empty/Blank Page to PdfDocument java

坚强是说给别人听的谎言 提交于 2019-12-11 15:26:57

问题


It is there any way to add a Blank Page to an existing PdfDocument ? I've created a method like this:

  public void addEmptyPage(PdfDocument pdfDocument){
    pdfDocument.addNewPage();
    pdfDocument.close();
}

However , when I use it with a PdfDocument , it throws :

com.itextpdf.kernel.PdfException: There is no associate PdfWriter for making indirects.
at com.itextpdf.kernel.pdf.PdfObject.makeIndirect(PdfObject.java:228) ~[kernel-7.1.1.jar:?]
at com.itextpdf.kernel.pdf.PdfObject.makeIndirect(PdfObject.java:248) ~[kernel-7.1.1.jar:?]
at com.itextpdf.kernel.pdf.PdfPage.<init>(PdfPage.java:104) ~[kernel-7.1.1.jar:?]
at com.itextpdf.kernel.pdf.PdfDocument.addNewPage(PdfDocument.java:416) ~[kernel-7.1.1.jar:?]

Which is the correct way to insert a Blank page into a pdf document?


回答1:


com.itextpdf.kernel.PdfException: There is no associate PdfWriter for making indirects.

That exception indicates that you initialize your PdfDocument with only a PdfReader, no PdfWriter. You don't show your PdfDocument instantiation code but I assume you do something like this:

PdfReader reader = new PdfReader(SOURCE);
PdfDocument document = new PdfDocument(reader);

Such documents are for reading only. (Actually you can do some minor manipulations but nothing as big as adding pages.)

If you want to edit a PDF, initialize your PdfDocument with both a PdfReader and a PdfWriter, e.g.

PdfReader reader = new PdfReader(SOURCE);
PdfWriter writer = new PdfWriter(DESTINATION);
PdfDocument document = new PdfDocument(reader, writer);

If you want to store the edited file at the same location as the original file, you must not use the same file name as SOURCE in the PdfReader and as DESTINATION in the PdfWriter.

Either first write to a temporary file, close all participating objects, and then replace the original file with the temporary file:

PdfReader reader = new PdfReader("document.pdf");
PdfWriter writer = new PdfWriter("document-temp.pdf");
PdfDocument document = new PdfDocument(reader, writer);
...
document.close();
Path filePath = Path.of("document.pdf");
Path tempPath = Path.of("document-temp.pdf");
Files.move(tempPath, filePath, StandardCopyOption.REPLACE_EXISTING);

Or read the original file into a byte[] and initialize the PdfReader from that array:

PdfReader reader = new PdfReader(new ByteArrayInputStream(Files.readAllBytes(Path.of("document.pdf"))));
PdfWriter writer = new PdfWriter("document.pdf");
PdfDocument document = new PdfDocument(reader, writer);
...
document.close();


来源:https://stackoverflow.com/questions/58395872/add-empty-blank-page-to-pdfdocument-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!