书接上文,本文记录iText7实现PDF电子签章
1、keystore文件,生成自签名证书,猛戳:SpringBoot系列——启用https
打开cmd,执行以下命令
keytool -genkeypair -alias stamper -keypass 123456 -keyalg RSA -keysize 1024 -validity 365 -keystore e:/Java/stamper.keystore -storepass 1234562、印章图片,这里有个在线制作电子公章小工具:http://makepic.net/tool/signet.html
3、pom需要引入新依赖包
<!-- 条形码、电子签章 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>barcodes</artifactId>
<version>${itext7.version}</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>hyph</artifactId>
<version>${itext7.version}</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>${itext7.version}</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>sign</artifactId>
<version>${itext7.version}</version>
</dependency>
<!-- 加密软件包 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.69</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.69</version>
</dependency> /**
* 电子签章
* @param src 需要签章的pdf文件路径
* @param dest 签完章的pdf文件路径
*/
public static void sign(String src, String dest) {
final String KEYSTORE="E:\\Java\\stamper.keystore";//keystore文件路径
final char[] PASSWORD="123456".toCharArray();// keystore密码
final String STAMPER_SRC="E:\\Java\\stamper.gif";//印章图片路径
try (PdfReader reader=new PdfReader(src); FileOutputStream os=new FileOutputStream(dest);){
//读取keystore ,获得私钥和证书链 jks
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(new FileInputStream(KEYSTORE), PASSWORD);
String alias=ks.aliases().nextElement();
PrivateKey pk=(PrivateKey) ks.getKey(alias, PASSWORD);
Certificate[] chain=ks.getCertificateChain(alias);
//创建签章工具PdfSigner、设定数字签章的属性
PdfSigner stamper=new PdfSigner(reader, os, new StampingProperties());
PdfSignatureAppearance appearance=stamper.getSignatureAppearance();
appearance.setReason("签名原因:系统自动签名盖章");
appearance.setLocation("签名地点:xxx系统");
appearance.setContact("联系方式:huanzi.qch@qq.com");
//加盖图章图片
ImageData img=ImageDataFactory.create(STAMPER_SRC);
Image image=new Image(img);
appearance.setPageNumber(1);
appearance.setPageRect(new Rectangle(650, 50, image.getImageWidth(), image.getImageHeight()));
appearance.setSignatureGraphic(img);
appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
//No such provider: BC : 问题解决,加BC库支持
Security.addProvider(new BouncyCastleProvider());
//摘要算法
IExternalDigest digest=new BouncyCastleDigest();
//签名算法
IExternalSignature signature=new PrivateKeySignature(pk, DigestAlgorithms.SHA256, BouncyCastleProvider.PROVIDER_NAME);
//调用itext签名方法完成pdf签章
stamper.setCertificationLevel(1);
stamper.signDetached(digest,signature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
System.out.println("操作完成!");
}catch (Exception e){
e.printStackTrace();
System.err.println("操作异常...");
}
}我们用 test() 生成的简单PDF文件来进行电子签章测试
//测试
public static void main(String[] args) {
//test();
//html2pdf();
sign("E:\\Java\\test.pdf","E:\\Java\\test2.pdf");
}作者:huanzi-qch
出处:https://www.cnblogs.com/huanzi-qch
若标题中有“转载”字样,则本文版权归原作者所有。若无转载字样,本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利.
官网地址 The Leading PDF Library for Developers | iTextSelect a value to filter the results.QuoteQuoteQuoteQuoteQuoteQuoteQuoteQuoteQuoteQuoteiText pdf on facebookiText pdf on twitteriText pdf on youtubeiText pdf on linkediniText pdf on stackoverflow
重要说明
<dependency>
<!-- 会自动引用 itext 其他库,kernel,commons,io,forms,layout,svg,styled-xml-parser -->
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>5.0.2</version>
</dependency> // 获取 java 版本
String version=System.getProperty("java.specification.version");
// 获取系统类型
String platform=System.getProperty("os.name", "");
platform=platform.toLowerCase().contains("window") ? "win" : "linux";
// 当前程序目录
String current=System.getProperty("user.dir");
System.out.println(String.format("current=%s", current));
// html 文件路径
File index=Paths.get(current, "..", "index.html").toFile();
if (!index.exists()) {
System.out.println(String.format("file not exist,file=%s", index.getAbsolutePath()));
return;
}
try {
// 保存 pdf 文件路径
File file=Paths.get(current, String.format("java%s_%s.pdf", version, platform)).toFile();
// 转换设置
ConverterProperties options=new ConverterProperties();
// 设置根目录类型
String baseUri=Paths.get(current, "..").toUri().toString();
options.setBaseUri(baseUri);
// 设置字体
FontProvider fontProvider=new FontProvider();
fontProvider.addStandardPdfFonts();
fontProvider.addSystemFonts();
options.setFontProvider(fontProvider);
// 转换 html 文件
HtmlConverter.convertToPdf(index, file, options);
} catch (IOException e) {
throw new RuntimeException(e);
}itext-demo/java1.8_win.pdf · yjihrp/linux-html2pdf-demo - Gitee.com
itext-demo/java11_linux.pdf · yjihrp/linux-html2pdf-demo - Gitee.com
测试结果
下一篇 3-LINUX HTML 转 OPENPDF
喽,今天是一篇HTML to PDF速食指南。
Java 转换 HTML 到PDF有许多类库,今天我们介绍一下第三方免费的类库OpenPDF。
OpenPDF是免费的Java类库 ,遵从LGPL 和 MPL协议,所以基本上能够可以随意使用。OpenPDF是基于iTEXT的,目前来说也是维护的比较好的Java操作PDF的开源软件。
话不多说,且看所需要的依赖,
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-core</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>1.0.6</version>
</dependency>
jsoup可以将html文件转换成输入流等,也可以遍历html的DOM节点,提取元素及样式等。
本篇示例将以下html文件转换成pdf
<html>
<head>
<style>
.center_div {
border: 1px solid #404e94;
margin-left: auto;
margin-right: auto;
background-color: #f6d0ed;
text-align: left;
padding: 8px;
}
table {
width: 100%;
border: 1px solid black;
}
th, td {
border: 1px solid black;
}
body,html,input{font-family:"msyh";}
</style>
</head>
<body>
<div class="center_div">
<h1>Hello java North!</h1>
<div>
<p>convert html to pdf.</p>
</div>
<div>
<table>
<thead>
<th>ROLE</th>
<th>NAME</th>
<th>TITLE</th>
</thead>
<tbody>
<tr>
<td>MARKSMAN</td>
<td>ASHE</td>
<td>THE FROST ARCHER</td>
</tr>
<tr>
<td>MAGES</td>
<td>ANNIE</td>
<td>THE DARK CHILD</td>
</tr>
<tr>
<td>射手</td>
<td>凯塔琳</td>
<td>皮城女警</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
以上html用浏览器打开如下,乱码是因为中文字体不识别,下面转换的时候会加载对应的字体来进行转换。
使用Java转换HTML到PDF代码如下:
public class HtmlToPDFOpenSource {
public static void main(String[] args) throws IOException {
HtmlToPDFOpenSource htmlToPDFOpenSource=new HtmlToPDFOpenSource();
htmlToPDFOpenSource.generatePdfByOpenhtmltopdf();
}
private void generatePdfByOpenhtmltopdf() throws IOException {
File inputHtml=new File("E:\\javaNorth\\java-study-note\\javaOpenSource\\src\\main\\resources\\test.html");
//加载html文件
Document document=Jsoup.parse(inputHtml, "UTF-8");
document.outputSettings().syntax(Document.OutputSettings.Syntax.html);
//引入资源目录,可以单独引入css,图片文件等
String baseUri=FileSystems.getDefault()
.getPath("javaOpenSource\\src\\main\\resources")
.toUri().toString();
try (OutputStream os=new FileOutputStream("javaOpenSource\\src\\main\\resources\\testOpenLeagueoflegends1.pdf")) {
PdfRendererBuilder builder=new PdfRendererBuilder();
builder.withUri("javaOpenSource\\src\\main\\resources\\testOpenLeagueoflegends1.pdf");
builder.toStream(os);
builder.withW3cDocument(new W3CDom().fromJsoup(document), baseUri);
//引入指定字体,注意字体名需要和css样式中指定的字体名相同
builder.useFont(new File("javaOpenSource\\src\\main\\resources\\fonts\\msyh.ttf"),"msyh",1,BaseRendererBuilder.FontStyle.NORMAL, true);
builder.run();
}
}
}
使用Java代码转换成PDF如下(示例中使用了微软雅黑中文字体):
上述html文件中增加如下外部样式:
<link href="style.css" rel="stylesheet">
并在resources目录下添加style.css文件,重新生成PDF文件如下。
本片介绍了使用OpenPDF将html文件转换成PDF文件。同时也使用了自定义字体,外部样式。但是以下几点需要格外注意。
全部示例在此:https://github.com/javatechnorth/java-study-note/tree/master/javaOpenSource/src/main/java/pdf
文章来源:Java技术指北
*请认真填写需求信息,我们会在24小时内与您取得联系。