Java pdf和jpg互轉
阿新 • • 發佈:2018-12-19
pdfbox: jpg轉pdf:
/**
* 使用pdfbox將jpg轉成pdf
* @param jpgStream jpg輸入流
* @param pdfPath pdf檔案儲存路徑
* @throws IOException IOException
*/
public static void jpgToPdf(InputStream jpgStream, String pdfPath) throws IOException {
PDDocument pdDocument = new PDDocument();
BufferedImage image = ImageIO.read(jpgStream);
PDPage pdPage = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
pdDocument.addPage(pdPage);
PDImageXObject pdImageXObject = LosslessFactory.createFromImage(pdDocument, image);
PDPageContentStream contentStream = new PDPageContentStream(pdDocument, pdPage);
contentStream.drawImage(pdImageXObject, 0 , 0, image.getWidth(), image.getHeight());
contentStream.close();
pdDocument.save(pdfPath);
pdDocument.close();
}
pdfbox: pdf轉jpg:
static void pdfbox() throws IOException {
long start = System.currentTimeMillis();
//pdf路徑
URL url = new URL("file:///D:/1.pdf" );
InputStream stream = URLUtil.getStream(url);
// 載入解析PDF檔案
PDDocument doc = PDDocument.load(stream);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
PDPageTree pages = doc.getPages();
int pageCount = pages.getCount();
for (int i = 0; i < pageCount; i++) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bim, "jpg", os);
byte[] datas = os.toByteArray();
// InputStream is = new ByteArrayInputStream(datas);
//jpg檔案轉出路徑
FileUtil.writeBytes(datas, new File("d:/jpg/" + i + ".jpg"));
}
long end = System.currentTimeMillis();
long time = (end - start) / 1000;
System.out.println(StrUtil.format("pdf轉jpg耗時: {}s", time));
}
icepdf: pdf轉jpg
Document document = new Document();
document.setUrl(new URL(pdfUrl));
int pageNum = document.getNumberOfPages();
for (int i = 0; i < pageNum; i++) {
// 目前僅支援1對1的pdf->jpg
if (i != 0) {
continue;
}
// 3、pdf -> jpg
BufferedImage bim = (BufferedImage) document.getPageImage(i,
GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX,
rotation, scale);
os = new ByteArrayOutputStream();
ImageIO.write(bim, "jpg", os);
// 4、jpg -> fdfs
byte[] datas = os.toByteArray();
InputStream is = new ByteArrayInputStream(datas);