1
與PDFBox的-的Android,PDFBOX-機器人卡住:1.8.9.0PDFBOX-Android的頁面添加文本疊加
我打開一個PDF文件的第一頁,在書寫文字和導入此頁到最後的一個新的一頁文件。
問題是創建新的頁面時,它使用最後一個頁面包含以前的文字...
所以,第一頁是好的,但也的nextS疊加文本..
private File writeReport() {
File fileSource = new File(getActivity().getApplicationContext().getExternalCacheDir(), "fileSource.pdf");
// get file model in assets
InputStream inputAsset = null;
try {
inputAsset = getActivity().getApplicationContext().getResources().getAssets().open("file_model.pdf");
} catch (IOException e) {
e.printStackTrace();
}
// copy file model in fileSource
try {
OutputStream outputStream = new FileOutputStream(file);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = inputAsset.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputAsset.close();
} catch (IOException e) {
System.out.print("Copy assets : IOException" + e.getMessage());
}
File fileTarget = new File(getActivity().getApplicationContext().getCacheDir(), "fileTarget.pdf");
try {
PDFBoxResourceLoader.init(getActivity().getApplicationContext()); // init lib
PDDocument documentSource = PDDocument.load(fileSource);
PDDocument documentTarget = new PDDocument();
// iteration == a new page
for(int i=0 ; i < 3 ; i++)
{
PDPage page = documentSource.getDocumentCatalog().getPages().get(0);
PDPageContentStream contentStream = new PDPageContentStream(documentSource, page, true, true);
PDFont font1 = PDType1Font.HELVETICA;
float startY = page.getMediaBox().getUpperRightY();
float factor = 2.83f;
page.getStream();
// add text
contentStream.beginText();
contentStream.setFont(font1, 10);
contentStream.newLineAtOffset(factor * 60, startY - (factor * 53));
contentStream.showText("test text" + i);
contentStream.endText();
contentStream.close();
// import source page to output file-> Problem here ! new page contain old overlay text...
documentTarget.importPage(page);
}
documentTarget.save(fileTarget);
documentTarget.close();
documentSource.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileTarget;
}
有沒有一種辦法每次迭代都有新的頁面? 謝謝!
「它使用包含以前文本的最後一頁」來源或目標頁面的最後一頁? 「以前的文字」是什麼?以前的迭代?如果是這樣,那麼它就像預期的那樣,因爲你正在修改同一頁PDPage對象。 –
更好的解決方案(請先測試一下)將首先導入頁面,獲取返回的PDPage(它現在是一個新對象),並使用該參數添加額外的內容流。 –
感謝您的回覆! - 它使用包含上一次迭代文本的最後一個_destination_頁面。 我在想PDPage是在每次迭代中新創建的,因爲在循環中聲明瞭... - 我已經嘗試了您的解決方案但沒有成功:結果相同... – partout