maven
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.16</version>
</dependency>
PDF转图片(可能会有多张图片,所以里边有循环)
//PDF和图片同名
@SuppressWarnings("unchecked")
public static List pdf2img(String pdfPath, String name, String outPath) {
List l = new ArrayList();
try {
File file = new File(pdfPath + name);
PDDocument doc = PDDocument.load(file);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
String[] tempName = name.split("\\.");
String imgName = tempName[0];
for (int i = 0; i < doc.getPages().getCount(); i++) {
BufferedImage bim = pdfRenderer.renderImage(i, 1.38f);//缩放比,可以自己调整,当时为什么用1.38,忘了,应该也是网上查了的,对了刚好和地下图片转PDF的缩放比进行呼应
String imageName = outPath + imgName + "-" + i + ".png";
File outFile = new File(imageName);
ImageIO.write(bim, "png", outFile);
l.add(imageName);
}
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
return l;
}
图片转PDF(可以多张图片转一份PDF)
/**
* 图片转PDF
* @param inPathList 图片输入路径包含图片名集合
* @param outPath PDF输出路径包含PDF名
*/
public static void imgList2PDF2(List<String> inPathList,String outPath){
try {
FileOutputStream fos = new FileOutputStream(outPath);
//设置PDF的边距大小等
Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
PdfWriter.getInstance(doc, fos);
doc.open();
//循环遍历,往PDF画板中添加图片
for (int i=0;i<inPathList.size();i++) {
String inPath = inPathList.get(i);
Image image = Image.getInstance(inPath);
//设置缩放比,和上边的1.38呼应,1/1.38
float scalePercentage = (216 / 300f) * 100.0f;
//x,y轴缩放比
image.scalePercent(scalePercentage, scalePercentage);
doc.add(image);
//添加到PDF哪一页,1开始
doc.setPageCount(i+1);
}
doc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
HTML转PDF(没测过,之前不知道哪里看到,随便带上的)(原理也大概相同,只是转的工具类不同)
public static void html2PDF(String html, String pdfPath) throws IOException, DocumentException {
ByteArrayInputStream is = new ByteArrayInputStream(html.getBytes());
File file = new File(pdfPath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
FileOutputStream os = new FileOutputStream(pdfPath);
Document document = new Document(PageSize.A4, 70, 70, 70, 100);
PdfWriter writer = PdfWriter.getInstance(document, os);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is,
XMLWorkerHelper.class.getResourceAsStream("/default.css"), Charset.forName("UTF-8"),
new AsianFontProvider());
document.close();
writer.close();
is.close();
os.close();
}