读取HTML文件,用Pdfbox库解析并转换成PDF文件
suiw9 2024-11-17 01:41 16 浏览 0 评论
更多编程技术文章,请查阅IOKKS - 专业编程技术分享平台
在本文中,我们将确保读取我们放在指定文件夹中的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);
}
}
}
服务
ConvertHtmlToPdfService.java服务包含一个名为convertHtmlToPdf的方法。convertHtmlToPdf方法接受字符串variableValue输入。
在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方法,当我们完成时,我们关闭缓冲区。
我们可以将我们的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文件中,如下所示。
<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.pdf文件被创建在output文件夹下。
因此,我们可以看到使用openhtmltopdf-pdfbox库进行平滑的HTML到PDF转换过程。
相关推荐
- 俄罗斯的 HTTPS 也要被废了?(俄罗斯网站关闭)
-
发布该推文的ScottHelme是一名黑客,SecurityHeaders和ReportUri的创始人、Pluralsight作者、BBC常驻黑客。他表示,CAs现在似乎正在停止为俄罗斯域名颁发...
- 如何强制所有流量使用 HTTPS一网上用户
-
如何强制所有流量使用HTTPS一网上用户使用.htaccess强制流量到https的最常见方法可能是使用.htaccess重定向请求。.htaccess是一个简单的文本文件,简称为“.h...
- https和http的区别(https和http有何区别)
-
“HTTPS和HTTP都是数据传输的应用层协议,区别在于HTTPS比HTTP安全”。区别在哪里,我们接着往下看:...
- 快码住!带你十分钟搞懂HTTP与HTTPS协议及请求的区别
-
什么是协议?网络协议是计算机之间为了实现网络通信从而达成的一种“约定”或“规则”,正是因为这个“规则”的存在,不同厂商的生产设备、及不同操作系统组成的计算机之间,才可以实现通信。简单来说,计算机与网络...
- 简述HTTPS工作原理(简述https原理,以及与http的区别)
-
https是在http协议的基础上加了一层SSL(由网景公司开发),加密由ssl实现,它的目的是为用户提供对网站服务器的身份认证(需要CA),以至于保护交换数据的隐私和完整性,原理如图示。1、客户端发...
- 21、HTTPS 有几次握手和挥手?HTTPS 的原理什么是(高薪 常问)
-
HTTPS是3次握手和4次挥手,和HTTP是一样的。HTTPS的原理...
- 一次安全可靠的通信——HTTPS原理
-
为什么HTTPS协议就比HTTP安全呢?一次安全可靠的通信应该包含什么东西呢,这篇文章我会尝试讲清楚这些细节。Alice与Bob的通信...
- 为什么有的网站没有使用https(为什么有的网站点不开)
-
有的网站没有使用HTTPS的原因可能涉及多个方面,以下是.com、.top域名的一些见解:服务器性能限制:HTTPS使用公钥加密和私钥解密技术,这要求服务器具备足够的计算能力来处理加解密操作。如果服务...
- HTTPS是什么?加密原理和证书。SSL/TLS握手过程
-
秘钥的产生过程非对称加密...
- 图解HTTPS「转」(图解http 完整版 彩色版 pdf)
-
我们都知道HTTPS能够加密信息,以免敏感信息被第三方获取。所以很多银行网站或电子邮箱等等安全级别较高的服务都会采用HTTPS协议。...
- HTTP 和 HTTPS 有何不同?一文带你全面了解
-
随着互联网时代的高速发展,Web服务器和客户端之间的安全通信需求也越来越高。HTTP和HTTPS是两种广泛使用的Web通信协议。本文将介绍HTTP和HTTPS的区别,并探讨为什么HTTPS已成为We...
- HTTP与HTTPS的区别,详细介绍(http与https有什么区别)
-
HTTP与HTTPS介绍超文本传输协议HTTP协议被用于在Web浏览器和网站服务器之间传递信息,HTTP协议以明文方式发送内容,不提供任何方式的数据加密,如果攻击者截取了Web浏览器和网站服务器之间的...
- 一文让你轻松掌握 HTTPS(https详解)
-
一文让你轻松掌握HTTPS原文作者:UC国际研发泽原写在最前:欢迎你来到“UC国际技术”公众号,我们将为大家提供与客户端、服务端、算法、测试、数据、前端等相关的高质量技术文章,不限于原创与翻译。...
- 如何在Spring Boot应用程序上启用HTTPS?
-
HTTPS是HTTP的安全版本,旨在提供传输层安全性(TLS)[安全套接字层(SSL)的后继产品],这是地址栏中的挂锁图标,用于在Web服务器和浏览器之间建立加密连接。HTTPS加密每个数据包以安全方...
- 一文彻底搞明白Http以及Https(http0)
-
早期以信息发布为主的Web1.0时代,HTTP已可以满足绝大部分需要。证书费用、服务器的计算资源都比较昂贵,作为HTTP安全扩展的HTTPS,通常只应用在登录、交易等少数环境中。但随着越来越多的重要...
你 发表评论:
欢迎- 一周热门
-
-
Linux:Ubuntu22.04上安装python3.11,简单易上手
-
宝马阿布达比分公司推出独特M4升级套件,整套升级约在20万
-
MATLAB中图片保存的五种方法(一)(matlab中保存图片命令)
-
别再傻傻搞不清楚Workstation Player和Workstation Pro的区别了
-
Linux上使用tinyproxy快速搭建HTTP/HTTPS代理器
-
如何提取、修改、强刷A卡bios a卡刷bios工具
-
Element Plus 的 Dialog 组件实现点击遮罩层不关闭对话框
-
日本组合“岚”将于2020年12月31日停止团体活动
-
SpringCloud OpenFeign 使用 okhttp 发送 HTTP 请求与 HTTP/2 探索
-
tinymce 号称富文本编辑器世界第一,大家同意么?
-
- 最近发表
- 标签列表
-
- dialog.js (57)
- importnew (44)
- windows93网页版 (44)
- yii2框架的优缺点 (45)
- tinyeditor (45)
- qt5.5 (60)
- windowsserver2016镜像下载 (52)
- okhttputils (51)
- android-gif-drawable (53)
- 时间轴插件 (56)
- docker systemd (65)
- slider.js (47)
- android webview缓存 (46)
- pagination.js (59)
- loadjs (62)
- openssl1.0.2 (48)
- velocity模板引擎 (48)
- pcre library (47)
- zabbix微信报警脚本 (63)
- jnetpcap (49)
- pdfrenderer (43)
- fastutil (48)
- uinavigationcontroller (53)
- bitbucket.org (44)
- python websocket-client (47)