有两种方法可以帮助您将图片插入到PDF文档中。第一钟是调用PDFPage.addImageFromFilePath接口。您可以参考如下示例代码,该代码将图片插入到PDF文档的首页:
备注:在调用PDFPage.addImageFromFilePath接口之前,您需要获取并解析将要添加图片的页面。
String path = "mnt/sdcard/input_files/sample.pdf"; try { // Initialize a PDFDoc object with the path to the PDF file. PDFDoc document = new PDFDoc(path); // Load the unencrypted document content. document.load(null); // Get the first page of the PDF file. PDFPage page = document.getPage(0); // Parse the page. if (!page.isParsed()) { Progressive parse = page.startParse(e_ParsePageNormal, null, false); int state = Progressive.e_ToBeContinued; while (state == Progressive.e_ToBeContinued) { state = parse.resume(); } } // Add an image to the first page. page.addImageFromFilePath("mnt/sdcard/input_files/2.png", new PointF(20, 30), 60, 50, true); // Save the document that has added the image. document.saveAs("mnt/sdcard/input_files/sample_image.pdf", PDFDoc.e_SaveFlagNormal); } catch (Exception e) { e.printStackTrace(); }
第二种是使用PDFPage.addAnnot接口在指定的页面添加一个stamp,然后将图片转换为位图,并将位图设置给刚添加的stamp注释。您可以参考以下的示例代码,该代码将图片作为stamp注释插入到PDF文件的首页:
String path = "mnt/sdcard/input_files/sample.pdf"; try { // Initialize a PDFDoc object with the path to the PDF file. PDFDoc document = new PDFDoc(path); // Load the unencrypted document content. document.load(null); // Get the first page of the PDF file. PDFPage page = document.getPage(0); // Add a stamp annotation to the first page. Stamp stamp = new Stamp(page.addAnnot(Annot.e_Stamp, new RectF(100, 350, 250, 150))); // Load a local image and convert it to a Bitmap. Bitmap bitmap = BitmapFactory.decodeFile("mnt/sdcard/input_files/2.png"); // Set the bitmap to the added stamp annotation. stamp.setBitmap(bitmap); //Reset appearance stream. stamp.resetAppearanceStream(); // Save the document that has added the stamp annotation. document.saveAs("mnt/sdcard/input_files/sample_image.pdf", PDFDoc.e_SaveFlagNormal); } catch (Exception e) { e.printStackTrace(); }