Spire.Doc for Java 3.6.7 已发布。该版本主要修复了加载文档、转Word为PDF、插入和更新目录时出现的一些问题。问题修复详情如下。
问题修复:
Word 文档编辑限制是对文档设置的可添加密码的保护,用于限制可对文档执行的编辑操作。通过设置编辑限制,用户能够精确控制文档中哪些部分可被编辑,以及可以执行何种类型的编辑。这种限制可以确保重要信息不被更改,同时也允许对文档其他部分进行指定类型的编辑,在合作编辑、信息收集等工作中非常方便。然而,文档管理者有时也需要取消编辑限制,以便纠正文档错误、更新文档信息或者按照新的使用需求进行文档修改。本文将介绍如何使用 Spire.Doc for Java 通过 Java 程序在 Word 文档中设置和取消编辑限制。
首先,您需要在 Java 程序中添加 Spire.Doc.jar 文件作为依赖项。您可以从此链接下载 JAR 文件;如果您使用 Maven,则可以通过在 pom.xml 文件中添加以下代码导入 JAR 文件。
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>14.9.5</version>
</dependency>
</dependencies>
Spire.Doc for Java 支持对 Word 文档设置四种类型的编辑限制:不允许任何更改(只读)、修订、批注和填写窗体。这些编辑限制可通过 Document.protect() 方法和一些枚举来设置,设置时还支持添加密码以阻止随意取消限制。
下面列出了用于设置编辑限制的枚举及其说明。
| 枚举 | 限制类型 | 描述 |
| ProtectionType.Allow_Only_Reading | 不允许任何更改(只读) | 只允许阅读文档。 |
| ProtectionType.Allow_Only_Revisions | 修订 | 只允许添加修订到文档。 |
| ProtectionType.Allow_Only_Comments | 批注 | 只允许添加批注到文档。 |
| ProtectionType.Allow_Only_Form_Fields | 填写窗体 | 只允许填写文档窗体。 |
| ProtectionType.No_Protection | 无限制 | 允许对文档进行任何编辑。 |
在 Word 文档中设置带密码的编辑限制的具体操作步骤如下:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.ProtectionType;
public class setEditingRestriction {
public static void main(String[] args) {
//创建一个Document类的对象
Document doc = new Document();
//加载一个Word文档
doc.loadFromFile("示例.docx");
//设置限制类型为只读,并添加密码
doc.protect(ProtectionType.Allow_Only_Reading, "password");
//设置限制类型为只能添加批注,并添加密码
//doc.protect(ProtectionType.Allow_Only_Comments, "password");
//设置限制类型为只能填写窗体,并添加密码
//doc.protect(ProtectionType.Allow_Only_Form_Fields, "password");
//设置限制类型为只能进行修订,并添加密码
//doc.protect(ProtectionType.Allow_Only_Revisions, "password");
//保存文档
doc.saveToFile("编辑限制.docx", FileFormat.Auto);
}
}
在设置 Word 文档的编辑限制时,用户可以通过插入允许编辑区域的起始和结束标记来添加例外项(不受限制的区域)。具体操作步骤如下:
import com.spire.doc.*;
public class setRegionalEditingRestrictions {
public static void main(String[] args) {
//创建一个Document类的对象
Document doc = new Document();
//加载一个Word文档
doc.loadFromFile("示例.docx");
//创建允许编辑区域的开始和结束标记
PermissionStart start = new PermissionStart(doc, "permission1");
PermissionEnd end = new PermissionEnd(doc, "permission1");
//获取文档第一个节
Section section = doc.getSections().get(0);
//在文档中插入允许编辑区域开始标记和结束标记
section.getParagraphs().get(0).getChildObjects().insert(0,start);
section.getParagraphs().get(5).getChildObjects().add(end);
//设置编辑限制并添加密码
doc.protect(ProtectionType.Allow_Only_Reading, "password");
//保存文档
doc.saveToFile("例外项.docx", FileFormat.Auto);
}
}
取消编辑限制可以通过将编辑限制设置为无限制来实现,从而允许对文档进行任何编辑。具体操作步骤如下:
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
public class removeEditingRestriction {
public static void main(String[] args) {
//创建一个Document类的对象
Document doc = new Document();
//加载一个Word文档
doc.loadFromFile("例外项.docx");
//移除编辑限制
doc.protect(ProtectionType.No_Protection);
//找到权限开始标记和结束标记并将其移除
for(int j=0;j<doc.getSections().getCount();j++){
//获取一个节
Section section=doc.getSections().get(j);
for(int k=0;k<section.getParagraphs().getCount();k++){
//获取节中的一个段落
Paragraph paragraph=section.getParagraphs().get(k);
for(int i=0;i<paragraph.getChildObjects().getCount();){
//获取段落的一个子对象
DocumentObject obj=paragraph.getChildObjects().get(i);
//判断子对象是否是PermissionStart或PermissionEnd类的实例
if(obj instanceof PermissionStart||obj instanceof PermissionEnd){
//如果是,则移除该子对象
paragraph.getChildObjects().remove(obj);
}else{
i++;
}
}
}
}
//保存文档
doc.saveToFile("取消编辑限制.docx", FileFormat.Auto);
}
}
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
该文将介绍如何使用Spire.PDF for Java绘制虚线和实线到PDF文档。
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
public class DrawLines {
public static void main(String[] args) {
//创建PdfDocument实例并添加一页
PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.getPages().add();
//设置线条位置和宽度
float x = 150;
float y = 100;
float width = 300;
//设置画笔颜色和宽度
PdfPen pen = new PdfPen(new PdfRGBColor(Color.red), 3f);
PdfPen pen1 = new PdfPen(new PdfRGBColor(Color.blue), 1f);
//设置虚线样式
pen.setDashStyle(PdfDashStyle.Dash);
pen.setDashPattern(new float[]{1, 1, 1});
//绘制虚线和实线
page.getCanvas().drawLine(pen, x, y, x + width, y);
page.getCanvas().drawLine(pen1, x, y+50, x + width, y+50);
//保存文档
pdf.saveToFile("output/drawLines_out.pdf");
}
}
PDF文档中绘制虚线和实线效果图:

本文介绍使用Spire.Presentation for Java来自定义PPT中的项目符号样式,即通过加载指定logo图片来设置为符号样式。
import com.spire.presentation.*;
import com.spire.presentation.IAutoShape;
import com.spire.presentation.drawing.FillFormatType;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
public class CustomStyle {
public static void main(String[] args) throws Exception{
//实例化Presentation类的对象
Presentation ppt = new Presentation();
//获取第一张幻灯片(新建的PPT文档默认包含一张幻灯片)
ISlide slide = ppt.getSlides().get(0);
//添加shape到幻灯片
IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(200,50,200,150));
shape.getTextFrame().getParagraphs().clear();//删除形状中默认的段落
shape.getShapeStyle().getLineColor().setColor(Color.white);//设置形状边框颜色
shape.getFill().setFillType(FillFormatType.NONE);//形状无背景填充
shape.getTextFrame().setText("开发\n测试\n技术支持\n销售\n综合");//添加文本到形状
//遍历shape中的所有段落
for (int i = 0; i< shape.getTextFrame().getParagraphs().getCount();i++)
{
ParagraphEx paragraph = shape.getTextFrame().getParagraphs().get(i);//获取段落
paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.black);
paragraph.setBulletType(TextBulletType.PICTURE);//设置项目符号样式为图片
BufferedImage image = ImageIO.read(new File("g.png"));//加载图片
paragraph.getBulletPicture().setEmbedImage(ppt.getImages().append(image));//添加图片作为项目符号样式
}
//保存文档
ppt.saveToFile("CustomStyle.pptx", FileFormat.PPTX_2013);
ppt.dispose();
}
}
添加效果:

对于需要在企业级应用中生成动态文档、财务报表或法律文书的开发者而言,HTML 到 PDF 的高质量转换是一项核心需求。无论是构建 Web 应用后端、自动化报告系统还是电子发票生成工具,确保内容在不同平台和设备上保持一致的格式和布局至关重要。
本文将演示如何使用功能强大的 Spire.PDF for .NET 库和 QT WebEngine 在 Java 中转换 HTML 到 PDF,确保从动态网页、原始 HTML 字符串或 HTML 文件中高保真地渲染出 PDF。
目录:
在 Java 环境中处理 HTML 到 PDF 的转换,能够充分发挥以下优势:
使用 Spire.PDF for Java 搭配 QT WebEngine 可构建专业级转换工具,具体安装步骤如下:
支持两种安装方式,开发者可根据项目需求选择:
1. Maven 依赖配置
在项目的 pom.xml 中添加以下仓库与依赖:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>11.7.0</version>
</dependency>
</dependencies>
2. 手动导入 JAR 包
从官方网站下载最新版 Spire.PDF for Java,解压后将 JAR 文件添加至项目的类路径。
QT WebEngine 作为基于 Chromium 的渲染引擎,是解析现代网页内容的核心组件。本场景使用开源版本的 Qt WebEngine(基于 LGPLv3/GPL 许可)来将 HTML 内容渲染为 PDF。根据您的操作系统下载相应的 QT 插件版本:
解压后得到 "plugins" 文件夹(示例路径:F:\Plugin\plugins-windows-x64\plugins)。
环境特殊配置
#1. 安装 xvfb
Centos:yum install Xvfb
Ubuntu:apt-get install Xvfb
#2. 运行应用程序
xvfb-run java -jar HTMLToPDF.jar
通过以下 Java 代码将 HTML 网页(URL)转换为 PDF文档。适用于动态抓取网页快照。
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;
public class ConvertUrlToPdf {
public static void main(String[] args) {
// 指定 url 路径
String url = "https://www.baidu.com/";
// 指定输出文件路径
String fileName = "output/Url转Pdf.pdf";
// 指定插件路径
String pluginPath = "F:\\Plugin\\plugins-windows-x64\\plugins";
// 设置插件路径
HtmlConverter.setPluginPath(pluginPath);
// 将 URL 转换为 PDF
HtmlConverter.convert(url, fileName, true, 1000000, new
Size(1200f, 1000f), new
PdfMargins(0));
}
}
参数说明:
上述代码中,使用到的核心转换方法是 HtmlConverter.convert()。它接受以下 6 个参数:
| 参数 | 用途 |
|---|---|
| String url | 指定要转换的网页地址 |
| String fileName | 指定输出 PDF 文件的路径 |
| boolean enableJavaScript | 允许动态内容(如 AJAX、动画)。设置为 false 可禁用 |
| int timeout | 最大页面加载时间。可根据网站加载速度调整。 |
| Size pageSize | 设置输出 PDF 的页面大小 |
| PdfMargins margins | 设置输出 PDF 的页边距 |
转换结果:

对于程序中动态生成的 HTML 内容(如用户输入的富文本),可直接将 HTML 字符串转换为 PDF:
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.LoadHtmlType;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;
import java.io.IOException;
public class ConvertHtmlStringToPdf {
public static void main(String[] args) throws IOException {
// 指定 Html 字符串
String htmlString = "<html>" +
"<style> h1 {color: #FF5733;font-size: 24px;margin-top: 50px;} </style>" +
"<body>" +
"<h1>Hello, PDF!</h1>" +
"<p>将 HTML 字符串转换为 PDF 文档的简单示例.</p>" +
"<ul>" +
"<li>项目 1</li>" +
"<li>项目 2</li>" +
"<li>项目 3</li>" +
"</ul>" +
"</body></html>";
// 指定输出文件路径
String outputFile = "output/Html字符串转PDF.pdf";
// 指定插件路径
String pluginPath = "F:\\Plugin\\plugins-windows-x64\\plugins";
// 设置插件路径
HtmlConverter.setPluginPath(pluginPath);
// 将 HTML 字符串转换为 PDF
HtmlConverter.convert(htmlString, outputFile, true, 100000, new
Size(700, 900), new
PdfMargins(0), LoadHtmlType.Source_Code);
}
}
在这段代码中:
转换效果:

本示例展示了如何通过编程将本地 HTML 文件转换为 PDF 文档。适用于静态文档归档和设计复杂的出版物。
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.LoadHtmlType;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ConvertHtmlToPdf {
public static void main(String[] args) throws IOException {
// 调用自定义方法 HtmlToString() 将 HTML 文件转换为字符串
String htmlString = HtmlToString("input.html");
// 指定输出文件路径
String outputFile = "output/Html文件转Pdf.pdf";
// 指定插件路径
String pluginPath = "F:\\Plugin\\plugins-windows-x64\\plugins";
// 设置插件路径
HtmlConverter.setPluginPath(pluginPath);
// 将 HTML 字符串转换为 PDF
HtmlConverter.convert(htmlString, outputFile, true, 100000, new
Size(700, 900), new
PdfMargins(0), LoadHtmlType.Source_Code);
}
// 将 HTML 文件转换为字符串
public static String
HtmlToString(String filePath) throws IOException {
String path = filePath;
File file = new File(path);
FileReader fileReader = new FileReader(file);
BufferedReader
bufferedReader = new
BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String temp = "";
while ((temp = bufferedReader.readLine()) != null) {
stringBuilder.append(temp +
"\n");
}
bufferedReader.close();
String str = stringBuilder.toString();
return str;
}
}
注意:只有内联 CSS 样式和内部 CSS 样式可以在 PDF 上正确呈现。对于外部 CSS 样式表,请将其转换为内联或内部 CSS 样式。
核心转换流程
转换效果:

答:Qt WebEngine 提供了一个基于 Chromium 的渲染引擎,支持现代 HTML5、CSS3 和 JavaScript 特性,是实现高保真转换的核心依赖。
答:申请 30 天试用许可证,以去除水印并解除功能限制。
答:
将 Spire.PDF for Java 与 QT 插件相结合,仅需极少代码就能在 Java 环境中实现 HTML 到 PDF 的高效转换。无论源文件是 URL、字符串还是本地文档,本文都提供了详尽的操作说明与实用代码示例,助您轻松强化文档自动化工作流程。
点击查看 Spire.PDF for Java 在线文档,解锁更多 Java 操作 PDF 的强大功能,如数字签名、PDF/A 合规性等,让文档处理更全面高效。
Spire.PDF for Java 3.6.6 现已发布。该版本支持使用QT插件将HTML转换为PDF,也支持PDF签名添加时间戳时设置用户名和密码。除此之外,一些在转换PDF到Word以及提取文本、图片时出现的问题也得以成功解决。详情见下文。
新功能:
String url = "https://www.baidu.com";
String fileName = "D:/output.pdf";
String pluginPath = "D:/Qt/plugins_64";
HtmlConverter.setPluginPath(pluginPath);
HtmlConverter.convert(url,fileName);
IOCR loIOCR=(image)->{
String extractedText = "";
//OCR API
//extractedText = ...
return extractedText;
};
PdfDocument.setExportTextOCRHandler(loIOCR);
PdfDocument pdf=new PdfDocument();
pdf.loadFromFile(inputPath);
String text = "";
for (PdfPageBase page : (Iterable) pdf.getPages()) {
text += page.extractText();
}
FileWriter sw = new FileWriter(outputPath);
sw.write(text);
sw.flush();
sw.close();
pdf.close();
String url = "https://freetsa.org/tsr";
signature.configureTimestamp(url,"user_name","password");
问题修复:
signature.removeShowConfigureText(SignatureConfigureText.Distinguished_Name);
https://www.e-iceblue.cn/Downloads/Spire-PDF-JAVA.html
下载QT插件请点击:本文介绍使用Spire.PDF for Java加载图片来设置成PDF平铺图片背景的效果,也可以作为平铺图片水印来使用;一般设置文本水印时可设置倾斜效果,这里设置图片背景(水印)也可以设置倾斜效果,具体可参考代码示例。
import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTilingBrush;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
public class AddBackground {
public static void main(String[] args) {
//创建PdfDocument对象,并加载PDF测试文档
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("test.pdf");
//遍历文档每一页,加载图片,并设置成平铺背景(水印)
for (int i = 0; i < pdf.getPages().getCount();i++)
{
PdfPageBase page = pdf.getPages().get(i);
Dimension2D dimension2D = new Dimension();
dimension2D.setSize(page.getCanvas().getSize().getWidth()/4, page.getCanvas().getSize().getHeight()/3);
PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
brush.getGraphics().setTransparency(0.2f);
brush.getGraphics().translateTransform(brush.getSize().getWidth()/10,brush.getSize().getHeight()/10);
brush.getGraphics().rotateTransform(30);
PdfImage image =PdfImage.fromFile("logo.png");
brush.getGraphics().drawImage(image,brush.getSize().getWidth()-image.getWidth()/2,(brush.getSize().getHeight())/2);
Rectangle2D rectangle2D = new Rectangle2D.Float();
rectangle2D.setFrame(new Point(0,0),page.getCanvas().getClientSize());
page.getCanvas().drawRectangle(brush,rectangle2D);
}
//保存文档
pdf.saveToFile("SetTiledBackground.pdf");
pdf.dispose();
}
}
平铺图片背景(水印)效果:

本文将介绍如何使用Spire.Doc for Java调整Word页眉页脚的位置高度。
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
public class AdjustHeaderFooterDistance {
public static void main(String[] args){
//创建Document实例
Document doc = new Document();
//加载Word文档
doc.loadFromFile("Headers and Footers.docx");
//获取第一个节
Section section = doc.getSections().get(0);
//调整第一节中页眉的位置高度
section.getPageSetup().setHeaderDistance(100);
//调整第一节中页脚的位置高度
section.getPageSetup().setFooterDistance(100);
//保存结果文档
doc.saveToFile("Output.docx", FileFormat.Docx);
}
}
调整高度前后效果对比
页眉:

页脚:

Spire.Email 3.6.7现已发布。该版本新增了netcoreapp2.0, netcoreapp3.0, netstandard2.0, MonoAndroid 以及 Xamarin.iOS。但是请注意,新增的平台不支持 client.BeginSendOne 方法。详情参见下文。
新功能:
本文介绍如何使用Spire.XLS for Javal复制Excel中的单元格时只保留公式值。复制工作表或者带格式复制单元格可参考这篇文章。
import com.spire.xls.*;
import java.util.EnumSet;
public class CopyCellsValue {
public static void main(String[] args) {
//加载Excel工作簿
Workbook wb = new Workbook();
wb.loadFromFile("test.xlsx");
//获取工作表
Worksheet sheet = wb.getWorksheets().get(2);
//设置复制单元格选项为仅复制公式值
CopyRangeOptions copyOptions = CopyRangeOptions.OnlyCopyFormulaValue;
//复制指定单元格到目标单元格
sheet.copy(sheet.getCellRange("F3:G7"), sheet.getCellRange("I3:J7"), EnumSet.of(copyOptions));
//保存文档
wb.saveToFile("CopyCellsValue.xlsx",FileFormat.Version2013);
wb.dispose();
}
}
复制效果
复制前:

复制后:
