書接上文,本文記錄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 123456
2、印章圖片,這里有個在線制作電子公章小工具: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小時內與您取得聯系。