Java通过第三方工具实现Word、PPT转 PDF (easy)

满昊然
2023-12-01

        前言:通过第三方工具实现将word或者ppt转为pdf格式;

1、documents4j 实现word转pdf  附:(在线预览)

        <!-- documents4j word转pdf -->
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.1.5</version>
        </dependency>
public class WORDtoODF {

    public static boolean docxToPdf(String wordFilePath, String pdfFilePath) {
        boolean result = false;

        File inputFile = new File(wordFilePath);
        File outputFile = new File(pdfFilePath);
        try {
            InputStream inputStream = new FileInputStream(inputFile);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(inputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();

            outputStream.close();
            result = true;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/word2pdf")
    public void word2pdf(HttpServletResponse response) {


        String wordPath = "D:\\home\\word\\aaa.docx";
        String pdfPath = "D:\\home\\word\\需求分析报告.pdf";

        docxToPdf(wordPath,pdfPath);
        System.out.println("转换成功");
        File file = new File(pdfPath);
        ResponseUtil.onlineReader(file,response);
        System.out.println("执行完毕");
    }
}

1.1、在线预览工具

/**
 * 在线预览,附件下载 工具包
 */
public class ResponseUtil {
    public static void responseBrowser(File file, HttpServletResponse response) {
        //下面的是进行响应客户端的测试代码
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的

            System.out.println("file.getName()   >>>" + file.getName());

            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
            // response.setHeader("Content-Disposition", "inline;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
            System.out.println("file.getPath() >>>>>>" + file.getPath());

            OutputStream outputStream = null;

            outputStream = response.getOutputStream();

            byte[] bytes = new byte[2048];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件响应出错,读写出错");
        }

    }


    public static void onlineReader(File file, HttpServletResponse response) {
        if (file.exists()) {
            byte[] data = null;
            try {
                response.setHeader("Content-Disposition", "inline;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);

                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                System.out.println(e);
            }

        } else {
            System.out.println("文件不存在");
        }
    }
}

2、Apach POI实现ppt转pdf

 <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.0.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>
public class PPTtoPDF {
	private static final String path = "D:\\home\\ppt\\";

	public static void main(String[] args) throws Exception {


        System.out.println(new Date().toString());
        String wordPath = "D:\\home\\ppt\\eee.pptx";
        String pdfPath = "D:\\home\\ppt\\eee.pdf";


        File inputFile = new File(wordPath);
        File outputFile = new File(pdfPath);

        if (!outputFile.exists())
            outputFile.createNewFile();

        convertPPTToPDF(inputFile,outputFile);
        System.out.println(new Date().toString());
        System.out.println("转换成功");
	}


	public static boolean convertPPTToPDF(File file, File toFile) {
		try {
			Document pdfDocument = new Document();
			PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(toFile));
			FileInputStream is = new FileInputStream(file);
			HSLFSlideShow hslfSlideShow = convertPPTToPDFByPPT(is);
			double zoom = 2;
			if (hslfSlideShow == null) {
				is = new FileInputStream(file);
				XMLSlideShow ppt = convertPPTToPDFByPPTX(is);
				if (ppt == null) {
					throw new NullPointerException("This PPTX get data is error....");
				}
				Dimension pgsize = ppt.getPageSize();
				List<XSLFSlide> slide = ppt.getSlides();
				AffineTransform at = new AffineTransform();
				at.setToScale(zoom, zoom);
				pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
				pdfWriter.open();
				pdfDocument.open();
				PdfPTable table = new PdfPTable(1);
				for (XSLFSlide xslfSlide : slide) {
					BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
					Graphics2D graphics = img.createGraphics();
					graphics.setTransform(at);

					graphics.setPaint(Color.white);
					graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
					xslfSlide.draw(graphics);
					graphics.getPaint();
					Image slideImage = Image.getInstance(img, null);
					table.addCell(new PdfPCell(slideImage, true));
				}
				ppt.close();
				pdfDocument.add(table);
				pdfDocument.close();
				pdfWriter.close();
				System.out.println(file.getAbsolutePath() + "Powerpoint file converted to PDF successfully");
				return true;
			}

			Dimension pgsize = hslfSlideShow.getPageSize();
			List<HSLFSlide> slides = hslfSlideShow.getSlides();
			pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
			pdfWriter.open();
			pdfDocument.open();
			AffineTransform at = new AffineTransform();
			PdfPTable table = new PdfPTable(1);
			for (HSLFSlide hslfSlide : slides) {
				BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
				Graphics2D graphics = img.createGraphics();
				graphics.setTransform(at);

				graphics.setPaint(Color.white);
				graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
				hslfSlide.draw(graphics);
				graphics.getPaint();
				Image slideImage = Image.getInstance(img, null);
				table.addCell(new PdfPCell(slideImage, true));
			}
			hslfSlideShow.close();
			pdfDocument.add(table);
			pdfDocument.close();
			pdfWriter.close();
			System.out.println(file.getAbsolutePath() + "Powerpoint file converted to PDF successfully");
			return true;
		} catch (Exception e) {
			System.out.println(file.getAbsolutePath() + "--->" + e.getMessage());
			return false;
		}
	}

	private static XMLSlideShow convertPPTToPDFByPPTX(FileInputStream is) {
		try {
			return new XMLSlideShow(is);
		} catch (IOException e) {
			return null;
		}
	}

	private static HSLFSlideShow convertPPTToPDFByPPT(FileInputStream is) {
		try {
			return new HSLFSlideShow(is);
		} catch (Exception e) {
			return null;
		}
	}
}

 类似资料: