前言引入依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>4.0.5</version>
</dependency>
htmlstr 这里支持去读取html里面的内容,也可以让前端传输的值来做拼接
注意这里的document这个类一定要引入 com.itextpdf.layout.Document; 不然没法使用强转
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.element.IElement;
import com.itextpdf.layout.font.FontProvider;
public static void main(String[] args) {
String htmlStr = null;
InputStream inputStream = null;
PdfDocument pd = null;
try {
// 读取html的流
inputStream = new FileInputStream(new File("D:\\pdf\\wanning.html"));
// 流转换成字符串
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = inputStream.read(b)) != -1; ) {
out.append(new String(b, 0, n));
}
/* htmlStr = "";
String replace = htmlStr.replace("<", "<");
htmlStr = replace.replace(">", ">");*/
String pdffile = "D:\\pdf\\hantest2.pdf";
pd = new PdfDocument(new PdfWriter(new FileOutputStream(new File(pdffile))));
// 设置文件标题为fileName,web上展示的标题为此标题
pd.getDocumentInfo().setTitle(pdffile);
} catch (Exception e) {
e.printStackTrace();
}
Document document = new Document(pd, PageSize.A4);
try {
// 导入字体
FontProvider font = new FontProvider();
font.addFont("D:\\pdf\\SIMSUN.ttf");
ConverterProperties c = new ConverterProperties();
c.setFontProvider(font);
c.setCharset("utf-8");
// 设置页面边距 必须先设置边距,再添加内容,否则页边距无效
//document.setMargins(50, 0, 50, 0);
List<IElement> list = HtmlConverter.convertToElements(htmlStr, c);
for (IElement ie : list) {
document.add((IBlockElement) ie);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
document.close();
}
}
//整合的工具类
public static void htmlToPdf(String html, OutputStream outStream, String fontPath) {
PdfDocument pd = null;
Document document = null;
try {
pd = new PdfDocument(new PdfWriter(outStream));
// 导入字体
FontProvider font = new FontProvider();
font.addStandardPdfFonts();
font.addFont(fontPath);
ConverterProperties c = new ConverterProperties();
c.setFontProvider(font);
c.setCharset("utf-8");
// 设置页面边距 必须先设置边距,再添加内容,否则页边距无效
document = new Document(pd, PageSize.A4, true);
document.setMargins(50, 0, 40, 0);
List<IElement> list = HtmlConverter.convertToElements(html, c);
for (IElement ie : list) {
document.add((IBlockElement) ie);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
document.close();
}
}
这里是将图片的URL地址转化为stream的形式
//此处的urlPath是url的路径
public static InputStream getImageStream(String urlPath) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(urlPath).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
return inputStream;
}
} catch (IOException e) {
log.info("获取网络图片出现异常,图片路径为:" + url);
e.printStackTrace();
}
return null;
}
此处是将PDF合成PNG 变成一个PDF签名功能
/**
*
* @param pdfFilePath 被合成的PDF
* @param inputStream 签名PNG的流
* @param generateFinalPdfPath 生成新的PDF
*/
public static void pdfSynPng(String pdfFilePath,InputStream inputStream,String generateFinalPdfPath) {
try {
File file = new File(pdfFilePath);
FileOutputStream outputStream = new FileOutputStream(generateFinalPdfPath);
PdfReader reader = new PdfReader(new FileInputStream(file));
PdfStamper stamper = new PdfStamper(reader, outputStream);
//将签名图片放在pdf文件的最后一页
int numberOfPages = reader.getNumberOfPages();
PdfContentByte over = stamper.getOverContent(numberOfPages);
int n;
byte[] buffer = new byte[4096];
ByteArrayOutputStream output = new ByteArrayOutputStream();
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
//签名图片
Image contractSealImg = Image.getInstance(output.toByteArray());
over.saveState();
PdfGState pdfGState = new PdfGState();
over.setGState(pdfGState);
contractSealImg.setRotationDegrees(90);
contractSealImg.setAbsolutePosition(350,30); //设置图片位置
contractSealImg.scaleAbsolute(100, 180); //设置图片大小
over.addImage(contractSealImg); //将图片添加到pdf文件
over.restoreState();
stamper.setFormFlattening(true);
stamper.close();
reader.close();
outputStream.close();
}catch (Exception e){
log.error("异常信息:{}",e);
}
}
注意的坑位,这边字体一定到自己去网上找一个类似于这样的,千万不要在windows的自己的系统目录找字体,否则生成的PDF内容是空白格,或者是不显示
下载链接,本来想上传上来,但是无法有文件
https://www.freefonts.io/simsun-font/