FileOutputStream outputStream=null; try{ outputStream=new FileOutputStream(saveFilePath); PdfWriter writer = new PdfWriter(saveFilePath); PdfDocument pdfDoc = new PdfDocument(writer); pdfDoc.setDefaultPageSize(PageSize.A4); ConverterProperties converterProperties = new ConverterProperties(); FontProvider provider = new FontProvider(); provider.addFont("D:/home/file/static/fonts/SourceHanSansSC-Regular.otf"); provider.addStandardPdfFonts(); byte[] fontBytes = Files.readAllBytes(Paths.get("D:/home/file/static/fonts/SourceHanSansSC-Regular.otf")); PdfFont pdfFont = PdfFontFactory.createFont(fontBytes, PdfEncodings.IDENTITY_H, false); pdfDoc.addFont(pdfFont); converterProperties.setFontProvider(provider); converterProperties.setCharset("UTF-8"); pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new PDFBuilder(pdfFont,title,pdfTime,footLabel)); Document doc = HtmlConverter.convertToDocument(htmlData, pdfDoc, converterProperties); doc.close(); writer.close(); outputStream.close(); }catch(Exception ex){ throw new PDFException("PDF export to File fail",ex); }finally{ IOUtils.closeQuietly(outputStream); } 字体文件是思源黑体,生成pdf时,html有em标签的斜体样式,但是生成的pdf中文斜体样式没有了,怎么改
时间: 2024-02-14 21:08:12 浏览: 105
首先,要在`FontProvider`中添加思源黑体的斜体字体。在思源黑体字体文件所在的文件夹中,有一个名为SourceHanSansSC-Bold.otf的文件,它是思源黑体的粗体字体。我们可以在`FontProvider`中添加这个粗体字体,然后通过设置CSS样式的方式来实现斜体。
以下是修改后的代码示例:
```java
FileOutputStream outputStream=null;
try{
outputStream=new FileOutputStream(saveFilePath);
PdfWriter writer = new PdfWriter(saveFilePath);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.setDefaultPageSize(PageSize.A4);
ConverterProperties converterProperties = new ConverterProperties();
FontProvider provider = new FontProvider();
provider.addFont("D:/home/file/static/fonts/SourceHanSansSC-Regular.otf");//添加思源黑体常规字体
provider.addFont("D:/home/file/static/fonts/SourceHanSansSC-Bold.otf");//添加思源黑体粗体字体
provider.addStandardPdfFonts();
byte[] fontBytes = Files.readAllBytes(Paths.get("D:/home/file/static/fonts/SourceHanSansSC-Regular.otf"));
PdfFont pdfFont = PdfFontFactory.createFont(fontBytes, PdfEncodings.IDENTITY_H, false);
pdfDoc.addFont(pdfFont);
converterProperties.setFontProvider(provider);
converterProperties.setCharset("UTF-8");
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new PDFBuilder(pdfFont,title,pdfTime,footLabel));
//设置CSS样式,实现中文斜体
ConverterProperties cssProperties = new ConverterProperties();
CssAppliers cssAppliers = new DefaultCssAppliers();
cssAppliers.setItalic(new Chunk("", pdfFont).setItalic());
cssProperties.setCssAppliers(cssAppliers);
cssProperties.setFontProvider(provider);
Document doc = HtmlConverter.convertToDocument(htmlData, pdfDoc, cssProperties);
doc.close();
writer.close();
outputStream.close();
}catch(Exception ex){
throw new PDFException("PDF export to File fail",ex);
}finally{
IOUtils.closeQuietly(outputStream);
}
```
需要注意的是,在设置CSS样式时,我们通过`Chunk`类的`setItalic()`方法来实现斜体。
阅读全文