java创建pdf空白页,将空白页添加到PdfDocument Java

编程知识 行业动态 更新时间:2024-06-13 00:21:16

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.(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?

解决方案

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();

更多推荐

java创建pdf空白页,将空白页添加到PdfDocument Java

本文发布于:2023-03-31 13:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/372ee11e7cab07e370b42f48de5a3922.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空白页   pdf   java   PdfDocument   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!