There are two ways to convert HTML to PDF:
- xhtmlrenderer
- itext
1. Use xhtmlrenderer
Rely on
< the dependency > < groupId > org. Xhtmlrenderer < / groupId > < artifactId > flying saucer - PDF < / artifactId > < version > 9.1.18 < / version > </dependency>Copy the code
template.html
Java code
import com.lowagie.text.pdf.BaseFont; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; public class HtmlToPdf { private static final String resourcesDir = System.getProperty("user.dir") + "/src/main/resources"; public void htmlToPdf() throws Exception { String path = resourcesDir + "/template/template.html"; String destPath = resourcesDir + "/template/template.pdf"; ITextRenderer renderer = new ITextRenderer(); OutputStream os = new FileOutputStream(destPath); renderer.setDocument(new File(path)); ITextFontResolver resolver = renderer.getFontResolver(); AddFont (resourcesDir + "/font/simsun.ttc", basefont. IDENTITY_H, basefont.not_embedded); renderer.layout(); renderer.createPDF(os); os.close(); } public static void main(String[] args) throws Exception { new HtmlToPdf().htmlToPdf(); }}Copy the code
The generated PDF
Matters needing attention
- In HTML, you need to define the font family in the body, and the font defined should be exactly the same as the font used in the code.
- Do not introduce IText-related packages into your project, as Chinese may not be displayed.
2. Use the itext
Rely on
<dependency> <groupId>com.itextpdf</groupId> <artifactId> html2PDF </artifactId> <version>3.0.3</version> </dependency>Copy the code
template.html
Java code
import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider; import com.itextpdf.layout.font.FontProvider; import java.io.*; public class HtmlToPdf { private static final String resourcesDir = System.getProperty("user.dir") + "/src/main/resources"; public void htmlToPdf() throws Exception { String path = resourcesDir + "/template/template.html"; String destPath = resourcesDir + "/template/template.pdf"; ConverterProperties converterProperties = new ConverterProperties(); FontProvider dfp = new DefaultFontProvider(); // Add font library dfp.addDirectory("C:/Windows/Fonts"); converterProperties.setFontProvider(dfp); try (InputStream in = new FileInputStream(new File(path)); OutputStream out = new FileOutputStream(new File(destPath))){ HtmlConverter.convertToPdf(in, out, converterProperties); }catch (Exception e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception { new HtmlToPdf().htmlToPdf(); }}Copy the code
The resulting PDF is similar to the above
Matters needing attention:
- There is no need to specify fonts in HTML. You can import a local font library or use a specific font library in your code.
Code path:
Github.com/anyueStarry…