本文共 2273 字,大约阅读时间需要 7 分钟。
本文将介绍通过Java编程来实现PDF文档转换的方法。包括:
PDF转为Word
PDF转为图片
PDF转为Html
PDF转为SVG
4.1 将PDF每一页转为单个的SVG
4.2 将一个包含多页的PDF文档转为一个SVG
PDF转为XPS
PDF转为PDF/A
使用工具:Free Spire.PDF for Java(免费版)
Jar文件获取及导入:
方法1:通过官网下载。下载后,解压文件,并将lib文件夹下的Spire.Pdf.jar文件导入Java程序。
方法2:可通过maven仓库安装导入。参考。
(肯定是用maven导入更方便的吧哈哈哈哈)Java代码示例
【示例1】PDF 转WordPdfDocument pdf = new PdfDocument("test.pdf");pdf.saveToFile("ToWord.docx",FileFormat.DOCX);
【示例2】PDF转图片
支持的图片格式包括Jpeg, Jpg, Png, Bmp, Tiff, Gif, EMF等。这里以保存为Png格式为例。
import com.spire.pdf.*;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;public class PDFtoimage { public static void main(String[] args) throws IOException { PdfDocument pdf = new PdfDocument("test.pdf");BufferedImage image;for(int i = 0; i< pdf.getPages().getCount();i++){ image = pdf.saveAsImage(i); File file = new File( String.format("ToImage-img-%d.png", i)); ImageIO.write(image, "PNG", file);}pdf.close(); }}
【示例3】PDF转Html
PdfDocument pdf = new PdfDocument("test.pdf");pdf.saveToFile("ToHTML.html", FileFormat.HTML);
【示例4】PDF转SVG
1.转为单个svgPdfDocument pdf = new PdfDocument("test.pdf");pdf.saveToFile("ToSVG.svg", FileFormat.SVG);
2.多页pdf转为一个svg
PdfDocument pdf = new PdfDocument("sampe.pdf");pdf.getConvertOptions().setOutputToOneSvg(true);pdf.saveToFile("ToOneSvg.svg",FileFormat.SVG);
【示例5】PDF 转XPS
PdfDocument pdf = new PdfDocument("test.pdf");pdf.saveToFile("ToXPS.xps", FileFormat.XPS);
【示例6】PDF转PDF/A
import com.spire.pdf.*;import com.spire.pdf.graphics.PdfMargins;import java.awt.geom.Dimension2D;public class PDFtoPDFA { public static void main(String[]args){ //加载测试文档 PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("test.pdf"); //转换为Pdf_A_1_B格式 PdfNewDocument newDoc = new PdfNewDocument(); newDoc.setConformance(PdfConformanceLevel.Pdf_A_1_B); PdfPageBase page; for ( int i=0;i< pdf.getPages().getCount();i++) { page = pdf.getPages().get(i); Dimension2D size = page.getSize(); PdfPageBase p = newDoc.getPages().add(size, new PdfMargins(0)); page.createTemplate().draw(p, 0, 0); } //保存结果文件 newDoc.save("ToPDFA.pdf"); newDoc.close(); }}
本篇博客参考自:
转载地址:http://kifen.baihongyu.com/