且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将空白页添加到PdfDocument Java

更新时间:2023-12-01 22:41:28

com.itextpdf.kernel.PdfException:没有关联的PdfWriter用于进行间接调用.

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

该异常表明您仅使用PdfReader而不使用PdfWriter初始化PdfDocument.您没有显示您的PdfDocument实例化代码,但我认为您会执行以下操作:

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.)

如果要编辑 PDF,请同时用PdfReaderPdfWriter初始化PdfDocument,例如

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

如果要将编辑后的文件存储在与原始文件相同的位置, 您不得使用与PdfReader中的SOURCEPdfWriter中的DESTINATION相同的文件名.

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

或将原始文件读入byte[]并从该数组初始化PdfReader:

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