![](/img/trans.png)
[英]How to apply digital signature image at bottom left position in the last page of pdf using pdfbox?
[英]How to exactly position an Image inside an existing PDF page using PDFBox?
我可以在現有的 pdf 文檔中插入圖像,但問題是,
我正在使用以下代碼。
List<PDPage> pages = pdDoc.getDocumentCatalog().getAllPages();
if(pages.size() > 0){
PDJpeg img = new PDJpeg(pdDoc, in);
PDPageContentStream stream = new PDPageContentStream(pdDoc,pages.get(0));
stream.drawImage(img, 60, 60);
stream.close();
}
我想要第一頁上的圖像。
PDFBox 是一個處理 PDF 文件的低級庫。 您負責更多高級功能。 因此,在此示例中,您將從文檔的左下角開始將圖像放置在(60, 60)
處。 這就是stream.drawImage(img, 60, 60);
做。
如果您想將圖像移動到其他地方,您必須計算並提供所需的位置(可能來自使用page.findCropBox()
獲得的尺寸,或手動輸入您的位置)。
對於文本,PDF 文檔元素是絕對定位的。 沒有用於重排文本、浮動或類似內容的低級功能。 如果您將文字寫在圖像的頂部,它將被寫入圖像的頂部。
最后,為了讓您的頁面變白——您正在創建一個新的內容流,從而覆蓋您頁面的原始內容流。 您應該附加到已經可用的流。
相關行是:
PDPageContentStream stream = new PDPageContentStream( pdDoc, pages.get(0));
你應該做的是這樣稱呼它:
PDPageContentStream stream = new PDPageContentStream( pdDoc, pages.get(0), true, true);
第一個true
是是否追加 content ,最后一個true
(這里不重要)是是否壓縮流。
查看PDFBox 源中提供的AddImageToPDF示例。
試試這個
doc = PDDocument.load( inputFileName );
PDXObjectImage ximage = null;
ximage = new PDJpeg(doc, new FileInputStream( image )
PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get(0);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
contentStream.drawImage( ximage, 425, 675 );
contentStream.close();
這會在第一頁打印圖像。 如果您想在所有頁面中打印,只需以頁數為限制條件進行 for 循環。 這對我很有效!
這么晚的答案,但這適用於在 2020 年使用 Kotlin 進行研究的人:drawImage() 在其內部獲取浮點值,所以試試這個:
val file = File(getPdfFile(FILE_NAME))
val document = PDDocument.load(file)
val page = document.getPage(0)
val contentStream: PDPageContentStream
contentStream = PDPageContentStream(document, page, true, true)
// Define a content stream for adding to the PDF
val bitmap: Bitmap? = ImageSaver(this).setFileName("sign.png").setDirectoryName("signature").load()
val mediaBox: PDRectangle = page.mediaBox
val ximage: PDImageXObject = JPEGFactory.createFromImage(document, bitmap)
contentStream.drawImage(ximage, mediaBox.width - 4 * 65, 26f)
// Make sure that the content stream is closed:
contentStream.close()
// Save the final pdf document to a file
pdfSaveLocation = "$directoryPDF/$UPDATED_FILE_NAME"
val pathSave = pdfSaveLocation
document.save(pathSave)
document.close()
此鏈接為您提供有關PrintImageLocations 類的詳細信息。 此 PrintImageLocations 將為您提供圖像的 x 和 y 坐標。
用法:java org.apache.pdfbox.examples.util.PrintImageLocations input-pdf
我正在創建一個新的 PDF 並在循環中運行下面的代碼 - 在每頁和下面的坐標以及高度和寬度值中添加一個圖像對我來說效果很好。
其中out是 BufferedImage 參考變量
PDPage page = new PDPage();
outputdocument.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(outputdocument, page, AppendMode.APPEND, true);
PDImageXObject pdImageXObject = JPEGFactory.createFromImage(outputdocument, out);
contentStream.drawImage(pdImageXObject, 5, 2, 600, 750);
contentStream.close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.