此篇將講述 如何用java把 pdf轉成image。
一般而言,大家會最直覺的使用 Adobe Acrobat 開啟pdf,然後另存新檔,把檔案另存成 image。
原本以為,iText套件可以將 文字、圖檔…等資料轉成 pdf檔,也可以再把pdf轉成圖檔,google之後,找不到相關範例。
在此篇,會介紹一個好用的套件 PDFRenderer 來教導如何將 PDF 轉為圖檔。
=> 點我下載套件:PDF Renderer(官網): a 100% Java PDF renderer and viewer
點我前往觀看 PDFRenderer api
範例程式引述(點我前往完整觀看程式):
範例1:How do I show a PDF in my Swing Application
範例2:How do I draw a PDF into an Image?
---
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import java.awt.Image;
import java.awt.Rectangle;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.swing.*;
/**
* An example of drawing a PDF to an image.
*
* @author joshua.marinacci@sun.com
*/
public class ImageMain {
public static void setup() throws IOException {
//load a pdf from a byte buffer
File file = new File("test.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
// draw the first page to an image
PDFPage page = pdffile.getPage(0);
//get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0,0,
(int)page.getBBox().getWidth(),
(int)page.getBBox().getHeight());
//generate the image
Image img = page.getImage(
rect.width, rect.height, //width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
//show the image in a frame
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel(new ImageIcon(img)));
frame.pack();
frame.setVisible(true);
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
ImageMain.setup();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
---
主題3:How do I draw a PDF directly to my own Graphics2D object?
網站上的範例寫得很詳細,還不錯理解唷 ^ ^~
以上。
沒有留言:
張貼留言