PDF與IMAGE互相轉化
阿新 • • 發佈:2018-12-24
所需jar包
1、http://download.csdn.net/detail/flykos/9858599
2、http://download.csdn.net/detail/flykos/9858294
java實現PDF與IMAGE互相轉化程式碼
package jpg2pdf; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.util.Iterator; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.Page; import org.icepdf.core.util.GraphicsRenderingHints; import com.lowagie.text.Image; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfWriter; public class PdfImgUtil { /** * IMAGE轉PDF * @param imagePath 圖片路徑 * @param pdfPath pdf路徑 */ public static void Image2pdf(String imagePath, String pdfPath) { try { BufferedImage img = ImageIO.read(new File(imagePath)); FileOutputStream fos = new FileOutputStream(pdfPath); com.lowagie.text.Document doc = new com.lowagie.text.Document(null, 0, 0, 0, 0); doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); Image image = Image.getInstance(imagePath); PdfWriter.getInstance(doc, fos); doc.open(); doc.add(image); doc.close(); } catch (Exception e) { e.printStackTrace(); } } /** * PDF轉IMAGE * @param filepath pdf路徑 * @param imagepath 圖片路徑 * @param zoom * @throws Exception */ public static void Pdf2Image(String filepath, String imagepath, float zoom) { try { Document document = null; float rotation = 0f; document = new Document(); document.setFile(filepath); BufferedImage img = (BufferedImage) document.getPageImage(0, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, zoom); /** * 迭代器的遍歷 */ Iterator iter = ImageIO.getImageWritersBySuffix("jpg"); ImageWriter writer = (ImageWriter) iter.next(); File outFile = new File(imagepath);// + document.getNumberOfPages() + "." + "jpg" FileOutputStream out = new FileOutputStream(outFile); ImageOutputStream outImage = ImageIO.createImageOutputStream(out); writer.setOutput(outImage); writer.write(new IIOImage(img, null, null)); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // Image2pdf("E:\\test.jpg", "E:\\test.pdf"); // Pdf2Image("E:\\test.pdf", "E:\\test.png", 1); } }