首页>代码>SpringBoot Html转PDF SpringBoot转换网页为PDF>/springboot-pdf-master/src/main/java/com/example/demo/service/PdfFileCreator.java
package com.example.demo.service;

import com.example.demo.model.PdfFileRequest;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Simon
 */
@Service
public class PdfFileCreator {
    private static final Logger LOGGER = LoggerFactory.getLogger(PdfFileCreator.class);

    public void writePdfToResponse(PdfFileRequest fileRequest, HttpServletResponse response) {
        String pdfFileName = fileRequest.getFileName();
        requireNotNull(pdfFileName, "The file name of the created PDF must be set");
        requireNotEmpty(pdfFileName, "File name of the created PDF cannot be empty");

        String sourceHtmlUrl = fileRequest.getSourceHtmlUrl();
        requireNotNull(sourceHtmlUrl, "Source HTML url must be set");
        requireNotEmpty(sourceHtmlUrl, "Source HTML url cannot be empty");

        List<String> pdfCommand = Arrays.asList(
//                "wkhtmltopdf",
                "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe",
                sourceHtmlUrl,
                "-"
        );
        ProcessBuilder pb = new ProcessBuilder(pdfCommand);
        Process pdfProcess;
        try {
            pdfProcess = pb.start();
            try (InputStream in = pdfProcess.getInputStream()) {
                writeCreatedPdfFileToResponse(in, response);
                waitForProcessBeforeContinueCurrentThread(pdfProcess);
                requireSuccessfulExitStatus(pdfProcess);
                setResponseHeaders(response, fileRequest);
            } catch (Exception ex) {
                writeErrorMessageToLog(ex, pdfProcess);
                throw new RuntimeException("PDF generation failed");
            } finally {
                pdfProcess.destroy();
            }
        } catch (IOException ex) {
            throw new RuntimeException("PDF generation failed", ex);
        }
    }

    private void requireNotNull(String value, String message) {
        if (value == null) {
            throw new IllegalArgumentException(message);
        }
    }

    private void requireNotEmpty(String value, String message) {
        if (value.isEmpty()) {
            throw new IllegalArgumentException(message);
        }
    }

    private void writeCreatedPdfFileToResponse(InputStream in, HttpServletResponse response) throws IOException {
        OutputStream out = response.getOutputStream();
        IOUtils.copy(in, out);
        out.flush();
    }

    private void waitForProcessBeforeContinueCurrentThread(Process process) {
        try {
            process.waitFor(2, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }

    private void requireSuccessfulExitStatus(Process process) {
        if (process.exitValue() != 0) {
            throw new RuntimeException("PDF generation failed");
        }
    }

    private void setResponseHeaders(HttpServletResponse response, PdfFileRequest fileRequest) {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileRequest.getFileName() + "\"");
    }

    private void writeErrorMessageToLog(Exception ex, Process pdfProcess) throws IOException {
        LOGGER.error("Could not create PDF because an exception was thrown: ", ex);
        LOGGER.error("The exit value of PDF process is: {}", pdfProcess.exitValue());

        String errorMessage = getErrorMessageFromProcess(pdfProcess);
        LOGGER.error("PDF process ended with error message: {}", errorMessage);
    }

    private String getErrorMessageFromProcess(Process pdfProcess) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(pdfProcess.getErrorStream()));
            StringWriter writer = new StringWriter();

            String line;
            while ((line = reader.readLine()) != null) {
                writer.append(line);
            }
            return writer.toString();
        } catch (IOException ex) {
            LOGGER.error("Could not extract error message from process because an exception was thrown", ex);
            return "";
        }
    }

}
最近下载更多
WHY-small  LV15 2023年7月5日
492874606  LV1 2023年1月29日
tuotuotuo  LV1 2023年1月10日
gshnlj  LV15 2022年10月9日
最代码官方  LV168 2022年10月5日
最近浏览更多
citybird  LV4 前天
develop  LV10 6月2日
f22m1a2b2  LV17 5月31日
taoshen95  LV15 5月15日
2716804680  LV9 4月20日
2317696509  LV6 2023年12月15日
chenlie  LV2 2023年11月13日
内心向阳  LV4 2023年11月7日
13043860zj  LV16 2023年10月31日
pizizhang 2023年10月20日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友