上一次用java通过LibreOffice 实现简单的文档转pdf
这次我们把PDF转为图片 (PNG/JPG) 长图片 ,也就是把所有页面拼成一张长图,分享群里什么的比较方便.
还是讲核心,这里主要用到pdfbox。( 本文测试时用的是 3.0.1 )
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.1</version>
</dependency>
直接上代码:
package com.trydone.samples;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class PDF2Image {
public static void main(String[] args) throws IOException {
// 加载 PDF 文件
String pdfFile = "/Users/pinke/Documents/test.pdf";
String pngFile = "/Users/pinke/Documents/test.png";
convertToImage(pdfFile, pngFile, "png", 144); //可以是jpg,
}
/**
* PDF文件转换为长图
*
* @param pdfFile pdf 路径
* @param outputFile 保存文件
* @param formatName 格式 png|jpg 等其它 ImageIO 支持的格式
* @param dpi DPI
* @throws IOException 异常
*/
public static void convertToImage(String pdfFile, String outputFile, String formatName, int dpi) throws IOException {
PDDocument document = Loader.loadPDF(new File(pdfFile));
PDFRenderer renderer = new PDFRenderer(document);
long startTime = System.currentTimeMillis();
try {
PDPageTree pages = document.getPages();
float width = 0; // 合并后图片的宽度
float height = 0; // 合并后图片的高度
float spaceHeight = 5; //页面间距
// 获取每张原始图片的尺寸信息
double scale = dpi / 72.0F;
//算一下整张的大小
for (int i = 0; i < pages.getCount(); i++) {
PDPage page = pages.get(i);
PDRectangle bBox = page.getCropBox();
float heightPt = bBox.getHeight();
float widthPt = bBox.getWidth();
int widthPx = (int) Math.max(Math.floor(widthPt * scale), 1.0);
int heightPx = (int) Math.max(Math.floor(heightPt * scale), 1.0);
width = Math.max(widthPx, width);
height += heightPx;
if (i > 0) {
height += spaceHeight;
}
}
BufferedImage mergedImg = new BufferedImage(Math.round(width), Math.round(height),
BufferedImage.TYPE_INT_RGB);
Graphics g = mergedImg.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, Math.round(width), Math.round(height));
int yOffset = 0; // 当前位置的x偏移值
for (int i = 0; i < pages.getCount(); i++) {
// 渲染页面为 BufferedImage
BufferedImage image = renderer.renderImageWithDPI(i, dpi, ImageType.RGB);
int xOffset = (mergedImg.getWidth() - image.getWidth()) / 2; // 居中显示
g.drawImage(image, xOffset, yOffset, null);
yOffset += image.getHeight() + spaceHeight; //上加页面间距
}
g.dispose();
//写文件
ImageIO.write(mergedImg, formatName, new File(outputFile));
} finally {
System.out.println("用时:" + (System.currentTimeMillis() - startTime));
document.close();
}
}
}