將PDF轉換為圖片(支援PDF含有多頁內容)
阿新 • • 發佈:2019-02-18
/***
*
* @param source 原始檔
* @param target 目標檔案
* @param n 縮放係數
*/
private static void changePdfToImg(String source,String target,int n) {
try {
File file = new File(source);
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
BufferedImage tag = new BufferedImage(595 * 2, 842 * 2 * pdffile.getNumPages(), BufferedImage.TYPE_INT_RGB);
for (int i = 1; i <= pdffile.getNumPages(); i++) {
PDFPage page = pdffile.getPage(i);
java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
java.awt.Image img = page.getImage((int)rect.getWidth()* n, (int)rect.getHeight() * n, rect,
null,
true,
true
);
tag.getGraphics().drawImage(img, 0, (i-1)*rect.height*n, rect.width * n, rect.height * n, null);
}
FileOutputStream out = new FileOutputStream(target);
ImageIO.write(tag, "jpg", out);
out.close();
channel.close();
raf.close();
buf.clear();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
*
* @param source 原始檔
* @param target 目標檔案
* @param n 縮放係數
*/
private static void changePdfToImg(String source,String target,int n) {
try {
File file = new File(source);
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
BufferedImage tag = new BufferedImage(595 * 2, 842 * 2 * pdffile.getNumPages(), BufferedImage.TYPE_INT_RGB);
for (int i = 1; i <= pdffile.getNumPages(); i++) {
PDFPage page = pdffile.getPage(i);
java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
java.awt.Image img = page.getImage((int)rect.getWidth()* n, (int)rect.getHeight() * n, rect,
null,
true,
true
);
tag.getGraphics().drawImage(img, 0, (i-1)*rect.height*n, rect.width * n, rect.height * n, null);
}
FileOutputStream out = new FileOutputStream(target);
ImageIO.write(tag, "jpg", out);
out.close();
channel.close();
raf.close();
buf.clear();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}