【Java】itext 实现 html根据模板生成pdf 中文不显示/图片不显示问题解决
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.licensing.base.LicenseKey;
import com.itextpdf.styledxmlparser.css.media.MediaDeviceDescription;
import com.itextpdf.styledxmlparser.css.media.MediaType;
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.property.TextAlignment;
import com.itextpdf.layout.element.Paragraph;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class PdfGenerator {
public static void main(String[] args) throws IOException {
String htmlContent = "<html><body><p>你好,这是PDF生成示例。</p><img src='image.jpg' /></body></html>";
String pdfFilePath = "output.pdf";
LicenseKey.loadLicenseFile("E:/workspace/itextkey.xml"); // 加载itext的授权文件
PdfWriter writer = new PdfWriter(pdfFilePath);
// 设置中文字体
String fontPath = "E:/workspace/simsun.ttc";
PdfFontFactory.register(fontPath);
MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.PRINT);
List<IElement> elements = HtmlConverter.convertToElements(htmlContent, mediaDeviceDescription);
// 解决中文不显示的问题
for (IElement element : elements) {
if (element instanceof List) {
List list = (List) element;
for (ListLabel label : list.getListItems()) {
for (IBlockElement blockElement : label.getBlockElements()) {
processElement(blockElement);
}
}
} else {
processElement(element);
}
}
// 解决图片不显示的问题
Document document = new Document(writer);
for (IElement element : elements) {
if (element instanceof IBlockElement && "img".equals(((IBlockElement) element).getPropertyAsString(HtmlConverter.PROPERTY_TAG))) {
String imageUrl = ((IBlockElement) element).getPropertyAsString(HtmlConverter.PROPERTY_SRC);
InputStream imageStream = new FileInputStream(imageUrl);
评论已关闭