300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java将各类文件转换为pdf格式【图片 excel word等】

java将各类文件转换为pdf格式【图片 excel word等】

时间:2022-04-27 20:00:41

相关推荐

java将各类文件转换为pdf格式【图片 excel word等】

简单整理下笔记,几个简单的转换PDF的方法,涉及到图片,excel,word等测试可用。

目前图片和word的转换都可以使用,excel的转换有点麻烦。

一、图片转换为PDF文件

这个方法可以直接将图片转换为pdf格式,同时这种pdf都是静态的。

import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import javax.imageio.ImageIO;import com.itextpdf.text.BadElementException;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Image;import com.itextpdf.text.Rectangle;import com.itextpdf.text.pdf.PdfWriter;public class Img2Pdf {public static void main(String[] args) {try {String imagePath = "D:/00000.jpg";String pdfPath = "D:/0000.pdf";BufferedImage img = ImageIO.read(new File(imagePath));FileOutputStream fos = new FileOutputStream(pdfPath);Document doc = new 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 (IOException e) {e.printStackTrace();} }}

二、word转换为pdf格式

这个目前测试也是可用的,可以去掉水印,也不会有页数的限制。需要使用到aspose-words-jdk16-18.6.jar

import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import com.aspose.words.Document;import com.aspose.words.License;import com.aspose.words.SaveFormat;import com.itextpdf.text.pdf.PdfReader;public class wordtopdf {public static void main(String[] args) {doc2pdf("D:\\test.doc","D:\\ceshi2.pdf");//getposition("D:\\test.docx","D:\\ceshi2.pdf");}public static boolean getLicense() {boolean result = false;try {InputStream is =wordtopdf.class.getClassLoader().getResourceAsStream("license.xml");License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}public static void doc2pdf(String inPath, String outPath) {if (!getLicense()) {return;}FileOutputStream os =null;try {File file = new File(outPath); // 新建一个空白pdf文档os = new FileOutputStream(file);Document doc = new Document(inPath); // Address是将要被转化的word文档doc.save(os, SaveFormat.PDF);} catch (Exception e) {e.printStackTrace();}finally{if(os!=null){try {os.close();} catch (IOException e) {e.printStackTrace();}}}}}

三、excel转pdf格式

这个没有找到合适的,太过复杂的比较麻烦,就不贴出来了,简单的需要使用第三方公司提供的。他们提供的测试版只能转换三页。有需要的可以参考他们的官网。貌似对各个文档都有支持。

https://www.e-/

import com.spire.xls.Workbook;public class ExcelToPDF {public static void main(String[] args) {//加载Excel文档Workbook wb = new Workbook();//Workbook wb = new Workbook();wb.loadFromFile("D:\\test2.xlsx");//调用方法保存为PDF格式//wb.saveToFile("ToPDF.pdf",FileFormat.PDF);wb.saveToFile("D:\\ToPDF2.pdf");}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。