剛做這一塊的代碼(透明)圖片(JPG,PNG,GIF等)添加到PDF頁面PDFBOX:
/**
* Draw an image to the specified coordinates onto a single page. <br>
* Also scaled the image with the specified factor.
*
* @author Nick Russler
* @param document PDF document the image should be written to.
* @param pdfpage Page number of the page in which the image should be written to.
* @param x X coordinate on the page where the left bottom corner of the image should be located. Regard that 0 is the left bottom of the pdf page.
* @param y Y coordinate on the page where the left bottom corner of the image should be located.
* @param scale Factor used to resize the image.
* @param imageFilePath Filepath of the image that is written to the PDF.
* @throws IOException
*/
public static void addImageToPage(PDDocument document, int pdfpage, int x, int y, float scale, String imageFilePath) throws IOException {
// Convert the image to TYPE_4BYTE_ABGR so PDFBox won't throw exceptions (e.g. for transparent png's).
BufferedImage tmp_image = ImageIO.read(new File(imageFilePath));
BufferedImage image = new BufferedImage(tmp_image.getWidth(), tmp_image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
image.createGraphics().drawRenderedImage(tmp_image, null);
PDXObjectImage ximage = new PDPixelMap(document, image);
PDPage page = (PDPage)document.getDocumentCatalog().getAllPages().get(pdfpage);
PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);
contentStream.drawXObject(ximage, x, y, ximage.getWidth()*scale, ximage.getHeight()*scale);
contentStream.close();
}
例子:
public static void main(String[] args) throws Exception {
String pdfFilePath = "C:/Users/Nick/Desktop/pdf-test.pdf";
String signatureImagePath = "C:/Users/Nick/Desktop/signature.png";
int page = 0;
PDDocument document = PDDocument.load(pdfFilePath);
addImageToPage(document, page, 0, 0, 0.5f, signatureImagePath);
document.save("C:/Users/Nick/Desktop/pdf-test-neu.pdf");
}
這爲我工作使用jdk 1.7和bcmail-jdk16-140.jar,bcprov-jdk16-140.jar,commons-logging-1.1.3.jar,fontbox-1.8.3.jar,jempbox-1.8.3.jar和pdfbox-1.8。 3.jar。
以下答案的問題是,如果頁面的尺寸不同,定位將無法正常工作(左上對齊)。我需要在PDF文檔的每個頁面的頂部添加文本水印,而上述解決方案正是我所需要的,所以顛覆了這個解決方案。 –