当前位置:Java -> 使用Pdfbox库阅读HTML文件,解析并将其转换为PDF文件

使用Pdfbox库阅读HTML文件,解析并将其转换为PDF文件

在本文中,我们将确保读取我们放入指定文件夹的HTML文件,并解析其中的变量,并将其替换为其真实值。然后,我使用“openhtmltopdf-pdfbox”库修改了HTML文件。我们将涵盖将其转换为PDF文件。

首先,我们将读取我们决定的文件夹下的HTML文件,解析它,并将我们自己的动态值传递给HTML中相关的变量。我们将使用“openhtmltopdf-pdfbox”库的最新更新形式将HTML文件转换为PDF文件。

我希望这将对需要这方面帮助的人们有所帮助。您可以在您的Java项目中轻松进行转换。您可以在下面看到一个示例项目。

首先,我们将创建一个新的输入文件夹,我们将在其中读取我们的输入HTML 文件,并创建一个输出文件夹,我们将在其中编写PDF文件。

我们可以将HTML文件放在输入文件夹下。我们定义要在HTML文件中替换的键值。作为示例,此键值给出为#NAME#。可选地,在Java中,您可以用外部发送的值替换想要的键值。

input folder :  \ConvertHtmlToPDF\input

output folder:  \ConvertHtmlToPDF\output




<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html lang="tr">
  <head>
    <meta data-fr-http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </meta>
    <title>Convert to Html to Pdf</title>
    <style type="text/css">
      body {
        font-family: "Times New Roman", Times, serif;
        font-size: 40px;
      }
    </style>
  </head>
  <body topmargin="0" leftmargin="0" rightmargin="0" bottommargin="0">
    <table width="700" border="0" cellspacing="0" cellpadding="0" style="background-color: #1859AB;
                                 
                                 color: white;
                                 font-size: 14px;
                                 border-radius: 1px;
                                 line-height: 1em; height: 30px;">
      <tbody>
        <tr>
          <td>
            <strong style="color:#F8CD00;">   Hello </strong>#NAME#
          </td>
        </tr>
      </tbody>
    </table>
  </body>
</html>


创建一个新项目

我们正在创建一个新的Spring项目。我正在使用Intellj Idea

控制器 

为了在HTML中用值替换键,我们将从外部发送该值。我们将为此编写一个rest服务。

我们在Controller文件夹下创建"ConvertHtmlToPdfController.java"类。我们在Controller类内创建一个名为"convertHtmlToPdf"的get方法。我们可以像下面这样动态地将值传递给此方法。

package com.works.controller;

import com.works.service.ConvertHtmlToPdfService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("")
public class ConvertHtmlToPdfController {

    private final ConvertHtmlToPdfService convertHtmlToPdfService;

    public ConvertHtmlToPdfController(ConvertHtmlToPdfService convertHtmlToPdfService) {
        this.convertHtmlToPdfService = convertHtmlToPdfService;
    }

    @GetMapping("/convertHtmlToPdf/{variableValue}")
    public ResponseEntity<String> convertHtmlToPdf(@PathVariable @RequestBody String variableValue) {
        try {
            return ResponseEntity.ok(convertHtmlToPdfService.convertHtmlToPdf(variableValue));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}


服务 

package com.works.service.impl;

import com.works.service.ConvertHtmlToPdfService;
import com.works.util.ConvertHtmlToPdfUtil;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;

@Service("convertHtmlToPdfService")
public class ConvertHtmlToPdfServiceImpl implements ConvertHtmlToPdfService {

    private String setVariableValue(String htmlContent, String key, String value) {

        if (StringUtils.isNotEmpty(value)) {
            htmlContent = htmlContent.replaceAll("#" + key + "#", value);
        } else {
            htmlContent = htmlContent.replaceAll("#" + key + "#", "");
        }

        return htmlContent;
    }

    @Override
    public String convertHtmlToPdf(String variableValue) throws Exception {
        String inputFile = "/convertHtmlToPDF/input/input.html";
        String outputFile = "/convertHtmlToPDF/output/output.pdf";
        String fontFile = "/convertHtmlToPDF/input/times.ttf";

        try {
            String htmlContent = ConvertHtmlToPdfUtil.readFileAsString(inputFile);
            htmlContent = setVariableValue(htmlContent, "NAME", variableValue);
            ConvertHtmlToPdfUtil.htmlConvertToPdf(htmlContent, outputFile, fontFile);

        } catch (Exception e) {
            throw new Exception("convertHtmlToPdf - An error was received in the service : ", e);
        }
        return "success";
    }
}


ConvertHtmlToPdfService.java 服务包含一个名为convertHtmlToPdf的方法。convertHtmlToPdf方法接受字符串变量值的输入。

在convertHtmlToPdf服务方法中;

定义"inputFile"变量来读取输入文件夹下的HTML文件。我们可以为该变量给出要读取的输入html文件的URL。

定义"outputFile"变量以将PDF文件分配到输出文件夹。我们可以将输出文件夹的URL分配给该变量。

您也可以从外部读取字体文件。您可以从输入文件夹下面获取此文件。我们还可以将包含字体文件的URL分配给"fontFile"变量。

在上述代码行中,将包含输入内容的文件夹的URL给予"ConvertHtmlToPdfUtil.readFileAsString"方法,以便读取输入文件夹中的HTML文件。

             String htmlContent = ConvertHtmlToPdfUtil.readFileAsString(inputFile);


package com.works.util;

import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class ConvertHtmlToPdfUtil {

    public static void safeCloseBufferedReader(BufferedReader bufferedReader) throws Exception {
        try {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (IOException e) {
            throw new Exception("safeCloseBufferedReader  - the method got an error. " + e.getMessage());
        }
    }

    public static String readFileAsString(String filePath) throws Exception {
        BufferedReader br = null;
        String encoding = "UTF-8";

        try {

            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), encoding));

            StringBuilder fileContentBuilder = new StringBuilder();
            String line;

            while ((line = br.readLine()) != null) {
                if (fileContentBuilder.length() > 0) {
                    fileContentBuilder.append(System.getProperty("line.separator"));
                }
                fileContentBuilder.append(line);
            }

            return fileContentBuilder.toString();

        } catch (Exception e) {
            new Exception("readFileAsString - the method got an error." + e.getMessage(), e);
            return null;
        } finally {
            safeCloseBufferedReader(br);
        }
    }

    public static OutputStream htmlConvertToPdf(String html, String filePath, String fonts) throws Exception {
        OutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
            final PdfRendererBuilder pdfBuilder = new PdfRendererBuilder();
            pdfBuilder.useFastMode();
            pdfBuilder.withHtmlContent(html, null);
            String fontPath = fonts;
            pdfBuilder.useFont(new File(concatPath(fontPath, "times.ttf")), "Times", null, null, false);
            pdfBuilder.toStream(os);
            pdfBuilder.run();
            os.close();
        } catch (Exception e) {
            throw new Exception(e.getMessage(), e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
            }
        }
        return os;
    }

    public static String concatPath(String path, String... subPathArr) {
        for (String subPath : subPathArr) {
            if (!path.endsWith(File.separator)) {
                path += File.separator;
            }
            path += subPath;
        }

        return path;
    }
}


在ConvertHtmlToPdfUtil.readFileAsString方法中,使用FileInputStream读取HTML文件。使用InputStreamReader将其转换为字符集,然后使用BufferedReader将其放入内部缓冲区。

在BufferedReader中逐行读取字符,如下代码块所示。将所有HTML内容放入字符串变量。当完成时,使用safeCloseBufferedReader方法关闭缓冲区。

         br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), encoding));
            StringBuilder fileContentBuilder = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                if (fileContentBuilder.length() > 0) {
                    fileContentBuilder.append(System.getProperty("line.separator"));
                }
                fileContentBuilder.append(line);
            }
            return fileContentBuilder.toString();


我们可以将HTML内容发送到setVariableValue方法中,以便用从外部发送到服务的值替换我们在HTML中标记为#key#的键值。

    private String setVariableValue(String htmlContent, String key, String value) {
        if (StringUtils.isNotEmpty(value)) {
            htmlContent = htmlContent.replaceAll("#"+key+"#", value);
        }else {
            htmlContent = htmlContent.replaceAll("#"+key+"#", "");
        }
        return htmlContent;
    }


然后,在替换过程之后,我们可以调用ConvertHtmlToPdfUtil.htmlConvertToPdf方法将html URL文件转换为pdf输出。 如下所示,ConvertHtmlToPdfUtil.htmlConvertToPdf方法可以接收html内容,输出和字体输入。

我们可以将这些输入传递给该方法。

              ConvertHtmlToPdfUtil.htmlConvertToPdf(htmlContent, outputFile, fontFile);


ConvertHtmlToPdfUtil.htmlConvertToPdf方法内容;

我们将创建一个新的FileOutputStream。这将确定我们指定的output.pdf文件的创建。

PdfRendererBuilder类位于com.openhtmltopdf.pdfboxout库中。因此,我们必须将该库添加到pom.xml文件中,如下所示。

                 final PdfRendererBuilder pdfBuilder = new PdfRendererBuilder();


 Pom.xml

      <dependency>
            <groupId>com.openhtmltopdf</groupId>
            <artifactId>openhtmltopdf-pdfbox</artifactId>
            <version>1.0.10</version>
        </dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.1</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.works</groupId>
	<artifactId>convertHtmlToPDF</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>convertHtmlToPDF</name>
	<description>convertHtmlToPDF</description>
	<properties>
		<java.version>17</java.version>
		<spring-cloud.version>2022.0.3</spring-cloud.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>com.openhtmltopdf</groupId>
			<artifactId>openhtmltopdf-pdfbox</artifactId>
			<version>1.0.10</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
			<version>4.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<image>
						<builder>paketobuildpacks/builder-jammy-base:latest</builder>
					</image>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


 实现PdfRendererBuilder对象之后,我们可以将HTML参数设置为'withHtmlContent',将fontpath参数设置为'useFont'。我们可以将输出文件设置为toStream。最后,我们可以使用run方法运行它。

            pdfBuilder.useFastMode();
            pdfBuilder.withHtmlContent(html, null);
            String fontPath = fonts;
            pdfBuilder.useFont(new File(concatPath(fontPath, "times.ttf")), "Times", null, null, false);
            pdfBuilder.toStream(os);
            pdfBuilder.run();


pdfBuilder.run(); 方法运行后,我们应该看到output文件夹下创建了output.pdf文件。

因此,我们可以看到使用openhtmltopdf-pdfbox库进行顺畅的HTML到PDF转换过程。


推荐阅读: 5.迭代器Iterator是什么 

本文链接: 使用Pdfbox库阅读HTML文件,解析并将其转换为PDF文件