Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法使用PDFBox向现有PDF添加额外内容_Java_Pdfbox - Fatal编程技术网

Java 无法使用PDFBox向现有PDF添加额外内容

Java 无法使用PDFBox向现有PDF添加额外内容,java,pdfbox,Java,Pdfbox,我正在使用PdfBox生成pdf,其中包含必须用于我要生成的每个pdf的模板的现有pdf 但是,当我尝试加载模板pdf并希望在其中写入内容时,所有以前包含的内容都被删除了 所以我希望这两个内容都能显示出来 请提出解决方案 以下是我正在尝试执行的代码: //Loading an existing document File file = new File("/home/spaneos/ScoringReports-TM-110617.pdf"); PDDocument document = P

我正在使用PdfBox生成pdf,其中包含必须用于我要生成的每个pdf的模板的现有pdf

但是,当我尝试加载模板pdf并希望在其中写入内容时,所有以前包含的内容都被删除了

所以我希望这两个内容都能显示出来

请提出解决方案

以下是我正在尝试执行的代码:

//Loading an existing document 
File file = new File("/home/spaneos/ScoringReports-TM-110617.pdf"); 
PDDocument document = PDDocument.load(file); 

//Retrieving the pages of the document 
PDPage page = document.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
//Begin the Content stream 
contentStream.beginText(); 

//Setting the font to the Content stream
contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );

//Setting the leading
contentStream.setLeading(14.5f);

//Setting the position for the line
contentStream.newLineAtOffset(25, 725);

String text1 = "This is an example of adding text to a page in the pdf document.we can add as many lines";
String text2 = "as we want like this using the ShowText()  method of the ContentStream class";

//Adding text in the form of string
contentStream.showText(text1);
contentStream.newLine();
contentStream.showText(text2);

//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("/home/spaneos/Downloads/man-161282_960_720.png",document);

//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(document, page);

contentStream.endText();

System.out.println("Content added");

//Closing the PDPageContentStream object
contents.close();   

//Closing the content stream
contentStream.close();

//Saving the document 
document.save(System.getProperty("user.dir").concat("/PdfBox_Examples/sample.pdf"));

//Closing the document  
document.close();

您可以像这样创建
PDPageContentStream
实例

PDPageContentStream contentStream = new PDPageContentStream(document, page);
[...]
PDPageContentStream contents = new PDPageContentStream(document, page);
使用此构造函数创建它将用新的内容流替换任何现有的内容流。请改用这个:

PDPageContentStream contents = new PDPageContentStream(document, page, AppendMode.APPEND, true, true);
AppendMode.APPEND
此处告诉PDFBox追加新流,第一个
true
告诉它压缩流,第二个
true
告诉它在添加流的开始处重置图形状态


此外,您没有真正使用第二个内容流…

请包含您的代码。由于您的问题没有说明您的具体操作,我们只能说您做错了什么…是的,我现在添加了代码。