MAVEN依赖
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.2</version> </dependency>
代码片段
/**pdffile-文件,targetPath-生成图片保存位置,index文件的页数,water是否加水印*/
public static void pdfFileToImage(File pdffile, String targetPath, int index, boolean water) { try { FileInputStream instream = new FileInputStream(pdffile); InputStream byteInputStream = null; try { PdfReader reader = new PdfReader(instream); int pageCount = reader.getNumberOfPages(); ByteArrayInputStream swapStream = null; if (pageCount > 0) { if (water) { BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); PdfContentByte content; PdfGState gs = new PdfGState(); // 在内容下方加水印 ByteArrayOutputStream bos = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(reader, bos); // 水印加在内容上方 content = stamper.getOverContent(index + 1); // 设置透明度 gs.setFillOpacity(0.4f); content.beginText(); content.setFontAndSize(base, 50); content.setTextMatrix(70, 200); content.setColorFill(BaseColor.GRAY); content.showTextAligned(Element.ALIGN_CENTER, "这里是水印文字", 300, 250, 55); content.showTextAligned(Element.ALIGN_CENTER, "这里是水印文字", 300, 600, 55); content.endText(); stamper.setFormFlattening(true); stamper.close(); Document doc = new Document(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); PdfCopy copy = new PdfCopy(doc, bout); doc.open(); // 输出到doc for (int j = 1; j <= pageCount; j++) { copy.addPage(copy.getImportedPage(new PdfReader(bos.toByteArray()), j)); } // copy.addPage(copy.getImportedPage(new PdfReader(bos.toByteArray()), index+1)); doc.close(); swapStream = new ByteArrayInputStream(bout.toByteArray()); // index = 0; } PDDocument doc; if (swapStream == null) { // instream = new FileInputStream(pdffile); doc = PDDocument.load(pdffile); } else { doc = PDDocument.load(swapStream); } PDFRenderer renderer = new PDFRenderer(doc); BufferedImage image = renderer.renderImage(index, 2.0f); image.flush(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageOutputStream imOut; imOut = ImageIO.createImageOutputStream(bs); ImageIO.write(image, "png", imOut); byteInputStream = new ByteArrayInputStream(bs.toByteArray()); } reader.close(); } catch (IOException e) { e.printStackTrace(); } File uploadFile = new File(targetPath); FileOutputStream fops; fops = new FileOutputStream(uploadFile); fops.write(readInputStream(byteInputStream)); fops.flush(); fops.close(); byteInputStream.close(); } catch (Exception e) { e.printStackTrace(); } }