1. Dependence
<!-- itext7 --> <dependency> <groupId></groupId> <artifactId>kernel</artifactId> <version>7.2.4</version> </dependency> <dependency> <groupId></groupId> <artifactId>io</artifactId> <version>7.2.4</version> </dependency> <dependency> <groupId></groupId> <artifactId>forms</artifactId> <version>7.2.4</version> </dependency> <dependency> <groupId></groupId> <artifactId>layout</artifactId> <version>7.2.4</version> </dependency> <dependency> <groupId></groupId> <artifactId>svg</artifactId> <version>7.2.4</version> </dependency> <!-- font-asian ForitextUsing East Asian Fonts --> <dependency> <groupId></groupId> <artifactId>font-asian</artifactId> <version>7.2.4</version> </dependency> <!-- html2pdf For转换htmlforpdf --> <dependency> <groupId></groupId> <artifactId>html2pdf</artifactId> <version>4.0.1</version> </dependency>
2. Code
2.1. General method
/** * * @param pdf_path PDF file save path * @param pdf_name PDF file name * @param cookie User information * @param waterContent Watermark content * @return * @throws AppException */ public PmsLXPDF createHtmlToPDF(String pdf_path, String pdf_name, String cookie, String waterContent) throws AppException { ("Start createPDF"); PmsLXPDF pdf = new PmsLXPDF(); String pdfViewUrl = "This is the interface path, generate jsp template"; String url = (); ("createPDFMethod Gettingmeurl[{}]",url); (url + pdfViewUrl, pdf_path, cookie, waterContent); File file = new File(pdf_path); if (file == null || !()) { throw new AppException("The project report failed to generate pdf!"); } try { //You can do some saving operations } catch (Exception e) { ("Exception happened", e); } //((id)); ("createPDF ends"); return pdf; } /** * html to pdf * * @param srcPath html path, can be a path on the hard disk or a network path * @param destPath pdf save path * @return Return true if the conversion is successful */ public static boolean convert(String srcPath, String destPath, String cookie, String waterContent) { if (!(destPath)) { ("The target path PDF file already exists, and the PDF generation failed:" + destPath); return false; } ("convertMethod passed insrcPath[{}],cookie[{}]",srcPath,cookie); InputStream in = null; OutputStream out = null; HttpURLConnection connection = null; try { if (("http")) { ("convertMethod passed insrcPath[{}],Need to entercookiebranch of",srcPath); URL url = new URL(srcPath); int connectTimeout = (("xxx", "30000")); int readTimeout = (("xxx", "30000")); connection = (HttpURLConnection) (); // Set the timeout time to connect to the host server (connectTimeout); // Set the time to read the data returned remotely (readTimeout); if ((cookie)) { // Set cookies String cookies = "SESSION=".concat(cookie); ("Cookie", cookies); } // Connect and get response (); in = (); } else { ("convertMethod passed insrcPath[{}],进入了不需要登录branch of",srcPath); in = new FileInputStream(srcPath); } out = new ByteArrayOutputStream(); (in, out); } catch (Throwable t) { ("Reading this file failed:" + srcPath, t); return false; } finally { (in); (out); if (connection != null) { ();// Close the remote connection } } String html = (); converCreatPdf(destPath, cookie, html, waterContent); return true; } private static boolean converCreatPdf(String destPath, String cookie, String html, String waterContent) { try (OutputStream fos = new FileOutputStream(destPath)) { //Convert html to pdf PdfWriter pdfWriter = new PdfWriter(fos); PdfDocument pdfDoc = new PdfDocument(pdfWriter); // Unified page header settings String header = "I'm a header"; Header headerHandler = new Header(header); (PdfDocumentEvent.START_PAGE, headerHandler); // Unified footer settings Footer footerHandler = new Footer(); (PdfDocumentEvent.END_PAGE, footerHandler); if ((waterContent)) { // Add watermark PdfWaterMarker pdfWaterMarker = new PdfWaterMarker(waterContent); (PdfDocumentEvent.END_PAGE, pdfWaterMarker); } // You need to create a document instead of directly generating a pdf file (because directly generating a pdf file will close the stream) ConverterProperties converterProperties = getConverterProperties(cookie); Document document = (html, pdfDoc, converterProperties); // flush triggers the write operation, and the registered event handler will be triggered at this time (); // Only after the document object is finished writing can you start writing the total page number ("Total number of PDF pages:" + ().getNumberOfPages()); (pdfDoc); (); } catch (Throwable t) { ("Creating PDF failed:" + destPath, t); return false; } return true; } public static ConverterProperties getConverterProperties(String cookie) { ConverterProperties converterProperties = new ConverterProperties(); FontProvider fontProvider = getFontProvider(); (fontProvider); CookieResourceRetriever myResourceRetriever = new CookieResourceRetriever(cookie); (myResourceRetriever); return converterProperties; } public void writeTotal(PdfDocument pdf) { Canvas canvas = new Canvas(placeholder, pdf); (8); if (font != null) { // Settings support Chinese (); // Total number of pages written in placeholders (("/Total [%d] pages", ()), 0, descent, ); } (); }
2.2. Tools
public class HtmlPrittifier { /** * Standardize HTML to complete missing closed tags * * @param in * @param out */ public static void fixHtml(InputStream in, OutputStream out) { // obtain a new Tidy instance Tidy tidy = new Tidy(); // set desired config options using tidy setters (true); ("utf8"); (true); (1024); (true); (true); (false); ("utf8"); (false); // output document even if errors were found. Prevent some custom tags from matching and causing pdf not to output (true); // Do not convert uri to prevent Chinese in uri from being included, and will convert non-ascii codes to hexadecimal, resulting in the Chinese picture link not being found. (false); (in, out); } /** * Standardize HTML to complete missing closed tags * * @param htmlString */ @SneakyThrows public static String fixHtml(String htmlString) { ByteArrayInputStream in = new ByteArrayInputStream(("UTF-8")); ByteArrayOutputStream out = new ByteArrayOutputStream(); fixHtml(in, out); return (); } }
2.3. Watermark implementation method
private static PdfFont createDefaultFont() throws IOException { return ("STSong-Light", "UniGB-UCS2-H"); } protected static class PdfWaterMarker implements IEventHandler { private PdfFont font; private String waterContent; public PdfWaterMarker(String waterContent) { = waterContent; try { = createDefaultFont(); } catch (IOException e) { ("PDF Header failed to set Chinese fonts", e); } } @Override public void handleEvent(Event event) { PdfDocumentEvent docEvent = (PdfDocumentEvent) event; PdfDocument pdfDoc = (); PdfPage page = (); Rectangle pageSize = (); PdfCanvas pdfCanvas = new PdfCanvas((), (), pdfDoc); Canvas canvas = new Canvas(pdfCanvas, pageSize); // Set the watermark text content Paragraph waterMarker = new Paragraph(waterContent) .setFont(font) .setOpacity(0.15f)// Set transparency .setFontSize(16);// Text size /*for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { (waterMarker, (150 + i * 300), (160 + j * 150), (), , , 0.3f); } }*/ // Calculate the starting position and interval of the watermark float xStart = 1; float yStart = 1; float stepX = 150; float stepY = 150; //Draw watermark text loops on the page for (float x = xStart; x < (); x += stepX) { for (float y = yStart; y < (); y += stepY) { // Draw watermark text (waterMarker, x, y, (), , , 0.6f); } } // Close the stream (); } }
2.4. How to implement header
private static PdfFont createDefaultFont() throws IOException { return ("STSong-Light", "UniGB-UCS2-H"); } protected static class Header implements IEventHandler { private String header; private PdfFont font; public Header(String header) { = header; try { = createDefaultFont(); } catch (IOException e) { ("PDF Header failed to set Chinese fonts", e); } } @Override public void handleEvent(Event event) { PdfDocumentEvent docEvent = (PdfDocumentEvent)event; PdfDocument pdf = (); PdfPage page = (); Rectangle pageSize = (); Document doc = new Document(pdf); float leftMargin = (); float rightMargin = (); float bottomMargin = (); float topMargin = (); float height = (); float width = (); Canvas canvas = new Canvas(new PdfCanvas(page), pageSize); if (font != null) { // Settings support Chinese (); } (8); // Creates drawing canvas PdfCanvas pdfCanvas = new PdfCanvas(page); (0.1f); (leftMargin, height - topMargin + 3).lineTo(width - rightMargin, height - topMargin + 3) .stroke(); // Write text at position (header, width / 2, height - 30, ); (); } }
2.5. Footer implementation method
protected static class Footer implements IEventHandler { // Write the placeholder for the total page number protected PdfFormXObject placeholder; // Footer placeholder size private float side = 36; // Adjust the footer placeholder position to the right and move 1, and adjust the down and move 3 private float space = 1; private float descent = 3; private PdfFont font; public Footer() { = new PdfFormXObject(new Rectangle(0, 0, side, side)); try { = createDefaultFont(); } catch (IOException e) { ("PDF Footer failed to set Chinese font", e); } } @Override public void handleEvent(Event event) { PdfDocumentEvent docEvent = (PdfDocumentEvent)event; PdfDocument pdf = (); PdfPage page = (); int pageNumber = (page); Rectangle pageSize = (); (("Current processing page [%d]", pageNumber)); Document doc = new Document(pdf); float leftMargin = (); float rightMargin = (); float bottomMargin = (); float height = ().getHeight(); float width = ().getWidth(); // The footer position float x = width / 2; float y = bottomMargin / 2; // Creates drawing canvas PdfCanvas pdfCanvas = new PdfCanvas(page); Canvas canvas = new Canvas(pdfCanvas, pageSize); if (font != null) { // Settings support Chinese (); } (8); // Setting support for horizontal lines // (0.1f); (0.1f); (leftMargin, bottomMargin - 3).lineTo(width - rightMargin, bottomMargin - 3).stroke(); // Set support page number Paragraph p = new Paragraph().add(("Page [%d]", pageNumber)); (p, x, y, ); (); // Add placeholder to write to the total page number (placeholder, x + space, y - descent); (); }
3. JSP implements watermarking
Does not affect the code that has been generated before
<style> #watermark div { /* color: rgba(255, 0, 0, .1); */ color: rgba(0, 0, 255, .1); position: absolute; font-size: 24px; white-space: nowrap; transform: rotate(-30deg); -ms-transform: rotate(-30deg); /* IE 9 */ -moz-transform: rotate(-30deg); /* Firefox */ -webkit-transform: rotate(-30deg); /* Safari and Chrome */ -o-transform: rotate(-30deg); /* Opera */ } </style> <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: transparent; pointer-events: none; z-index: 99999999;"> </div> <script> var operatorName = '${}'; var erpId = '${}'; (function() { var w = ; var h = ; var r = (w * w + h * h); var i = 0; var j = 0; var watermark = ('#watermark'); var div; var top, left; for (var i = 0; i < 10; ++i) { for (var j = 0; j < 10; ++j) { div = ('div'); = 'No extrapolation:' + operatorName + '(' + erpId + ')'; top = i * 100 + 'px'; left = 500 * j - 50 - (i % 2 == 0 ? 250 : 0) + 'px'; ('top', top); ('left', left); (div); } } })(); </script>
The above is the detailed content of SpringBoot using iText7 to convert HTML into PDF and add header and footer watermarks. For more information about SpringBoot HTML to PDF, please follow my other related articles!