Skip to content

Instantly share code, notes, and snippets.

@bestK
Last active July 6, 2022 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bestK/fc9142c024fcec9c0b47c55b8bf2a6d0 to your computer and use it in GitHub Desktop.
Save bestK/fc9142c024fcec9c0b47c55b8bf2a6d0 to your computer and use it in GitHub Desktop.
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.util.List;
@Slf4j
public class PdfUtils {
public static void mergePdfFiles(List<byte[]> files, OutputStream outputStream)
throws IOException, DocumentException {
Document document = null;
PdfCopy copy = null;
try {
document = new Document(new PdfReader(files.get(0)).getPageSize(1));
copy = new PdfCopy(document, outputStream);
document.open();
for (byte[] file : files) {
PdfReader reader = new PdfReader(file);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
}
} finally {
if (null != document && document.getPageNumber() > 0) {
document.close();
}
if (copy != null) {
copy.close();
}
}
}
/**
* 使用 iText 生成 PDF 文档
*
* @param htmlTmpStr
* html 模板文件字符串
* @param fontFile
* 所需字体文件(相对路径+文件名)
*/
public static byte[] createPDF(String htmlTmpStr, String fontFile) throws IOException, DocumentException {
byte[] result;
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlTmpStr);
ITextFontResolver fontResolver = renderer.getFontResolver();
// 解决中文支持问题,需要所需字体(ttc)文件
fontResolver.addFont(ResourceFileUtil.getAbsolutePath(fontFile), BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(outputStream);
result = outputStream.toByteArray();
outputStream.flush();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment