JAVA-29281 Create new module Text Processing Libraries Modules (#15479)
This commit is contained in:
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.pdf;
|
||||
|
||||
import com.itextpdf.text.Document;
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.Paragraph;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.List;
|
||||
|
||||
public class DocxToPDFExample {
|
||||
|
||||
public static void main(String[] args) throws IOException, DocumentException {
|
||||
InputStream docxInputStream = new FileInputStream("input.docx");
|
||||
try (XWPFDocument document = new XWPFDocument(docxInputStream);
|
||||
OutputStream pdfOutputStream = new FileOutputStream("output.pdf");) {
|
||||
Document pdfDocument = new Document();
|
||||
PdfWriter.getInstance(pdfDocument, pdfOutputStream);
|
||||
pdfDocument.open();
|
||||
|
||||
List<XWPFParagraph> paragraphs = document.getParagraphs();
|
||||
for (XWPFParagraph paragraph : paragraphs) {
|
||||
pdfDocument.add(new Paragraph(paragraph.getText()));
|
||||
}
|
||||
pdfDocument.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.pdf;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.fit.pdfdom.PDFDomTree;
|
||||
|
||||
import com.itextpdf.text.Document;
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
import com.itextpdf.tool.xml.XMLWorkerHelper;
|
||||
|
||||
public class PDF2HTMLExample {
|
||||
|
||||
private static final String PDF = "src/main/resources/pdf.pdf";
|
||||
private static final String HTML = "src/main/resources/html.html";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
generateHTMLFromPDF(PDF);
|
||||
generatePDFFromHTML(HTML);
|
||||
} catch (IOException | ParserConfigurationException | DocumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generateHTMLFromPDF(String filename) throws ParserConfigurationException, IOException {
|
||||
PDDocument pdf = PDDocument.load(new File(filename));
|
||||
PDFDomTree parser = new PDFDomTree();
|
||||
Writer output = new PrintWriter("src/output/pdf.html", "utf-8");
|
||||
parser.writeText(pdf, output);
|
||||
output.close();
|
||||
if (pdf != null) {
|
||||
pdf.close();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generatePDFFromHTML(String filename) throws ParserConfigurationException, IOException, DocumentException {
|
||||
Document document = new Document();
|
||||
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("src/output/html.pdf"));
|
||||
document.open();
|
||||
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(filename));
|
||||
document.close();
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.pdf;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.rendering.ImageType;
|
||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
|
||||
|
||||
import com.itextpdf.text.BadElementException;
|
||||
import com.itextpdf.text.Document;
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.Image;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
|
||||
public class PDF2ImageExample {
|
||||
|
||||
private static final String PDF = "src/main/resources/pdf.pdf";
|
||||
private static final String JPG = "http://cdn2.baeldung.netdna-cdn.com/wp-content/uploads/2016/05/baeldung-rest-widget-main-1.2.0";
|
||||
private static final String GIF = "https://media.giphy.com/media/l3V0x6kdXUW9M4ONq/giphy";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
generateImageFromPDF(PDF, "png");
|
||||
generateImageFromPDF(PDF, "jpeg");
|
||||
generateImageFromPDF(PDF, "gif");
|
||||
generatePDFFromImage(JPG, "jpg");
|
||||
generatePDFFromImage(GIF, "gif");
|
||||
} catch (IOException | DocumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generateImageFromPDF(String filename, String extension) throws IOException {
|
||||
PDDocument document = PDDocument.load(new File(filename));
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
for (int page = 0; page < document.getNumberOfPages(); ++page) {
|
||||
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
|
||||
ImageIOUtil.writeImage(bim, String.format("src/output/pdf-%d.%s", page + 1, extension), 300);
|
||||
}
|
||||
document.close();
|
||||
}
|
||||
|
||||
private static void generatePDFFromImage(String filename, String extension)
|
||||
throws IOException, BadElementException, DocumentException {
|
||||
Document document = new Document();
|
||||
String input = filename + "." + extension;
|
||||
String output = "src/output/" + extension + ".pdf";
|
||||
FileOutputStream fos = new FileOutputStream(output);
|
||||
PdfWriter writer = PdfWriter.getInstance(document, fos);
|
||||
writer.open();
|
||||
document.open();
|
||||
document.add(Image.getInstance((new URL(input))));
|
||||
document.close();
|
||||
writer.close();
|
||||
}
|
||||
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.pdf;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import org.apache.pdfbox.cos.COSDocument;
|
||||
import org.apache.pdfbox.io.RandomAccessFile;
|
||||
import org.apache.pdfbox.pdfparser.PDFParser;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
|
||||
import com.itextpdf.text.Document;
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.Element;
|
||||
import com.itextpdf.text.Font;
|
||||
import com.itextpdf.text.PageSize;
|
||||
import com.itextpdf.text.Paragraph;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
|
||||
public class PDF2TextExample {
|
||||
|
||||
private static final String PDF = "src/main/resources/pdf.pdf";
|
||||
private static final String TXT = "src/main/resources/txt.txt";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
generateTxtFromPDF(PDF);
|
||||
generatePDFFromTxt(TXT);
|
||||
} catch (IOException | DocumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generateTxtFromPDF(String filename) throws IOException {
|
||||
File f = new File(filename);
|
||||
String parsedText;
|
||||
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
|
||||
parser.parse();
|
||||
|
||||
COSDocument cosDoc = parser.getDocument();
|
||||
|
||||
PDFTextStripper pdfStripper = new PDFTextStripper();
|
||||
PDDocument pdDoc = new PDDocument(cosDoc);
|
||||
|
||||
parsedText = pdfStripper.getText(pdDoc);
|
||||
|
||||
if (cosDoc != null)
|
||||
cosDoc.close();
|
||||
if (pdDoc != null)
|
||||
pdDoc.close();
|
||||
|
||||
PrintWriter pw = new PrintWriter("src/output/pdf.txt");
|
||||
pw.print(parsedText);
|
||||
pw.close();
|
||||
}
|
||||
|
||||
private static void generatePDFFromTxt(String filename) throws IOException, DocumentException {
|
||||
Document pdfDoc = new Document(PageSize.A4);
|
||||
PdfWriter.getInstance(pdfDoc, new FileOutputStream("src/output/txt.pdf"))
|
||||
.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
|
||||
pdfDoc.open();
|
||||
|
||||
Font myfont = new Font();
|
||||
myfont.setStyle(Font.NORMAL);
|
||||
myfont.setSize(11);
|
||||
pdfDoc.add(new Paragraph("\n"));
|
||||
|
||||
BufferedReader br = new BufferedReader(new FileReader(filename));
|
||||
String strLine;
|
||||
while ((strLine = br.readLine()) != null) {
|
||||
Paragraph para = new Paragraph(strLine + "\n", myfont);
|
||||
para.setAlignment(Element.ALIGN_JUSTIFIED);
|
||||
pdfDoc.add(para);
|
||||
}
|
||||
|
||||
pdfDoc.close();
|
||||
br.close();
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.pdf;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.BreakType;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
|
||||
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
|
||||
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
|
||||
|
||||
public class PDF2WordExample {
|
||||
|
||||
private static final String FILENAME = "src/main/resources/pdf.pdf";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
generateDocFromPDF(FILENAME);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void generateDocFromPDF(String filename) throws IOException {
|
||||
XWPFDocument doc = new XWPFDocument();
|
||||
|
||||
String pdf = filename;
|
||||
PdfReader reader = new PdfReader(pdf);
|
||||
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
|
||||
|
||||
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
|
||||
TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
|
||||
String text = strategy.getResultantText();
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
XWPFRun run = p.createRun();
|
||||
run.setText(text);
|
||||
run.addBreak(BreakType.PAGE);
|
||||
}
|
||||
FileOutputStream out = new FileOutputStream("src/output/pdf.docx");
|
||||
doc.write(out);
|
||||
out.close();
|
||||
reader.close();
|
||||
doc.close();
|
||||
}
|
||||
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.pdf;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.itextpdf.text.BadElementException;
|
||||
import com.itextpdf.text.BaseColor;
|
||||
import com.itextpdf.text.Document;
|
||||
import com.itextpdf.text.Element;
|
||||
import com.itextpdf.text.Image;
|
||||
import com.itextpdf.text.Phrase;
|
||||
import com.itextpdf.text.pdf.PdfPCell;
|
||||
import com.itextpdf.text.pdf.PdfPTable;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
|
||||
public class PDFSampleMain {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try {
|
||||
|
||||
Document document = new Document();
|
||||
PdfWriter.getInstance(document, new FileOutputStream("iTextTable.pdf"));
|
||||
|
||||
document.open();
|
||||
|
||||
PdfPTable table = new PdfPTable(3);
|
||||
addTableHeader(table);
|
||||
addRows(table);
|
||||
addCustomRows(table);
|
||||
|
||||
document.add(table);
|
||||
document.close();
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void addTableHeader(PdfPTable table) {
|
||||
Stream.of("column header 1", "column header 2", "column header 3")
|
||||
.forEach(columnTitle -> {
|
||||
PdfPCell header = new PdfPCell();
|
||||
header.setBackgroundColor(BaseColor.LIGHT_GRAY);
|
||||
header.setBorderWidth(2);
|
||||
header.setPhrase(new Phrase(columnTitle));
|
||||
table.addCell(header);
|
||||
});
|
||||
}
|
||||
|
||||
private static void addRows(PdfPTable table) {
|
||||
table.addCell("row 1, col 1");
|
||||
table.addCell("row 1, col 2");
|
||||
table.addCell("row 1, col 3");
|
||||
}
|
||||
|
||||
private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException {
|
||||
Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
|
||||
Image img = Image.getInstance(path.toAbsolutePath().toString());
|
||||
img.scalePercent(10);
|
||||
|
||||
PdfPCell imageCell = new PdfPCell(img);
|
||||
table.addCell(imageCell);
|
||||
|
||||
PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
|
||||
horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
|
||||
table.addCell(horizontalAlignCell);
|
||||
|
||||
PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
|
||||
verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
|
||||
table.addCell(verticalAlignCell);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.pdf.openpdf;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.w3c.dom.Element;
|
||||
import org.xhtmlrenderer.extend.FSImage;
|
||||
import org.xhtmlrenderer.extend.ReplacedElement;
|
||||
import org.xhtmlrenderer.extend.ReplacedElementFactory;
|
||||
import org.xhtmlrenderer.extend.UserAgentCallback;
|
||||
import org.xhtmlrenderer.layout.LayoutContext;
|
||||
import org.xhtmlrenderer.pdf.ITextFSImage;
|
||||
import org.xhtmlrenderer.pdf.ITextImageElement;
|
||||
import org.xhtmlrenderer.render.BlockBox;
|
||||
import org.xhtmlrenderer.simple.extend.FormSubmissionListener;
|
||||
|
||||
import com.lowagie.text.Image;
|
||||
|
||||
public class CustomElementFactoryImpl implements ReplacedElementFactory {
|
||||
@Override
|
||||
public ReplacedElement createReplacedElement(LayoutContext lc, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) {
|
||||
Element e = box.getElement();
|
||||
String nodeName = e.getNodeName();
|
||||
if (nodeName.equals("img")) {
|
||||
String imagePath = e.getAttribute("src");
|
||||
try {
|
||||
InputStream input = new FileInputStream("src/main/resources/" + imagePath);
|
||||
byte[] bytes = IOUtils.toByteArray(input);
|
||||
Image image = Image.getInstance(bytes);
|
||||
FSImage fsImage = new ITextFSImage(image);
|
||||
if (cssWidth != -1 || cssHeight != -1) {
|
||||
fsImage.scale(cssWidth, cssHeight);
|
||||
} else {
|
||||
fsImage.scale(2000, 1000);
|
||||
}
|
||||
return new ITextImageElement(fsImage);
|
||||
} catch (Exception e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(Element e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFormSubmissionListener(FormSubmissionListener listener) {
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.pdf.openpdf;
|
||||
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.xhtmlrenderer.layout.SharedContext;
|
||||
import org.xhtmlrenderer.pdf.ITextRenderer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class Html2PdfUsingFlyingSaucer {
|
||||
|
||||
private static final String HTML_INPUT = "src/main/resources/htmlforopenpdf.html";
|
||||
private static final String PDF_OUTPUT = "src/main/resources/html2pdf.pdf";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
Html2PdfUsingFlyingSaucer htmlToPdf = new Html2PdfUsingFlyingSaucer();
|
||||
htmlToPdf.generateHtmlToPdf();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void generateHtmlToPdf() throws Exception {
|
||||
File inputHTML = new File(HTML_INPUT);
|
||||
Document inputHtml = createWellFormedHtml(inputHTML);
|
||||
File outputPdf = new File(PDF_OUTPUT);
|
||||
xhtmlToPdf(inputHtml, outputPdf);
|
||||
}
|
||||
|
||||
private Document createWellFormedHtml(File inputHTML) throws IOException {
|
||||
Document document = Jsoup.parse(inputHTML, "UTF-8");
|
||||
document.outputSettings()
|
||||
.syntax(Document.OutputSettings.Syntax.xml);
|
||||
return document;
|
||||
}
|
||||
|
||||
private void xhtmlToPdf(Document xhtml, File outputPdf) throws Exception {
|
||||
try (OutputStream outputStream = new FileOutputStream(outputPdf)) {
|
||||
ITextRenderer renderer = new ITextRenderer();
|
||||
SharedContext sharedContext = renderer.getSharedContext();
|
||||
sharedContext.setPrint(true);
|
||||
sharedContext.setInteractive(false);
|
||||
sharedContext.setReplacedElementFactory(new CustomElementFactoryImpl());
|
||||
renderer.setDocumentFromString(xhtml.html());
|
||||
renderer.layout();
|
||||
renderer.createPDF(outputStream);
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.pdf.openpdf;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.FileSystems;
|
||||
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.helper.W3CDom;
|
||||
import org.jsoup.nodes.Document;
|
||||
|
||||
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
|
||||
|
||||
public class Html2PdfUsingOpenHtml {
|
||||
|
||||
private static final String HTML_INPUT = "src/main/resources/htmlforopenpdf.html";
|
||||
private static final String PDF_OUTPUT = "src/main/resources/html2pdf.pdf";
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
Html2PdfUsingOpenHtml htmlToPdf = new Html2PdfUsingOpenHtml();
|
||||
htmlToPdf.generateHtmlToPdf();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void generateHtmlToPdf() throws IOException {
|
||||
File inputHTML = new File(HTML_INPUT);
|
||||
Document doc = createWellFormedHtml(inputHTML);
|
||||
xhtmlToPdf(doc, PDF_OUTPUT);
|
||||
}
|
||||
|
||||
private Document createWellFormedHtml(File inputHTML) throws IOException {
|
||||
Document document = Jsoup.parse(inputHTML, "UTF-8");
|
||||
document.outputSettings()
|
||||
.syntax(Document.OutputSettings.Syntax.xml);
|
||||
return document;
|
||||
}
|
||||
|
||||
private void xhtmlToPdf(Document doc, String outputPdf) throws IOException {
|
||||
try (OutputStream os = new FileOutputStream(outputPdf)) {
|
||||
String baseUri = FileSystems.getDefault()
|
||||
.getPath("src/main/resources/")
|
||||
.toUri()
|
||||
.toString();
|
||||
PdfRendererBuilder builder = new PdfRendererBuilder();
|
||||
builder.withUri(outputPdf);
|
||||
builder.toStream(os);
|
||||
builder.withW3cDocument(new W3CDom().fromJsoup(doc), baseUri);
|
||||
builder.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.pdfthymeleaf;
|
||||
|
||||
import com.lowagie.text.DocumentException;
|
||||
import org.thymeleaf.TemplateEngine;
|
||||
import org.thymeleaf.context.Context;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
import org.xhtmlrenderer.pdf.ITextRenderer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class PDFThymeleafExample {
|
||||
|
||||
public static void main(String[] args) throws IOException, DocumentException {
|
||||
PDFThymeleafExample thymeleaf2Pdf = new PDFThymeleafExample();
|
||||
String html = thymeleaf2Pdf.parseThymeleafTemplate();
|
||||
thymeleaf2Pdf.generatePdfFromHtml(html);
|
||||
}
|
||||
|
||||
public void generatePdfFromHtml(String html) throws IOException, DocumentException {
|
||||
String outputFolder = System.getProperty("user.home") + File.separator + "thymeleaf.pdf";
|
||||
OutputStream outputStream = new FileOutputStream(outputFolder);
|
||||
|
||||
ITextRenderer renderer = new ITextRenderer();
|
||||
renderer.setDocumentFromString(html);
|
||||
renderer.layout();
|
||||
renderer.createPDF(outputStream);
|
||||
|
||||
outputStream.close();
|
||||
}
|
||||
|
||||
private String parseThymeleafTemplate() {
|
||||
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
|
||||
templateResolver.setSuffix(".html");
|
||||
templateResolver.setTemplateMode(TemplateMode.HTML);
|
||||
|
||||
TemplateEngine templateEngine = new TemplateEngine();
|
||||
templateEngine.setTemplateResolver(templateResolver);
|
||||
|
||||
Context context = new Context();
|
||||
context.setVariable("to", "Baeldung.com");
|
||||
|
||||
return templateEngine.process("thymeleaf_template", context);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,53 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>A very simple webpage</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>A very simple webpage. This is an "h1" level header.</h1>
|
||||
|
||||
<h2>This is a level h2 header.</h2>
|
||||
|
||||
<h6>This is a level h6 header. Pretty small!</h6>
|
||||
|
||||
<p>This is a standard paragraph.</p>
|
||||
|
||||
<p align=center>Now I've aligned it in the center of the screen.</p>
|
||||
|
||||
<p align=right>Now aligned to the right</p>
|
||||
|
||||
<p><b>Bold text</b></p>
|
||||
|
||||
<p><strong>Strongly emphasized text</strong> Can you tell the difference vs. bold?</p>
|
||||
|
||||
<p><i>Italics</i></p>
|
||||
|
||||
<p><em>Emphasized text</em> Just like Italics!</p>
|
||||
|
||||
<h2>How about a nice ordered list!</h2>
|
||||
<ol>
|
||||
<li>This little piggy went to market</li>
|
||||
<li>This little piggy went to SB228 class</li>
|
||||
<li>This little piggy went to an expensive restaurant in Downtown Palo Alto</li>
|
||||
<li>This little piggy ate too much at Indian Buffet.</li>
|
||||
<li>This little piggy got lost</li>
|
||||
</ol>
|
||||
|
||||
<h2>Unordered list</h2>
|
||||
<ul>
|
||||
<li>First element</li>
|
||||
<li>Second element</li>
|
||||
<li>Third element</li>
|
||||
</ul>
|
||||
|
||||
|
||||
<p>And finally, how about some</p><a href="http://www.google.com/">Links?</a>
|
||||
|
||||
<p>Remember, you can view the HTMl code from this or any other page by using the "View Page Source" command of your browser.</p>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,26 @@
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
.center_div {
|
||||
border: 1px solid gray;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
width: 90%;
|
||||
background-color: #d0f0f6;
|
||||
text-align: left;
|
||||
padding: 8px;
|
||||
}
|
||||
</style>
|
||||
<link href="style.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="center_div">
|
||||
<h1>Hello Baeldung!</h1>
|
||||
<img src="Java_logo.png">
|
||||
|
||||
<div class="myclass">
|
||||
<p>This is the tutorial to convert html to pdf.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
.myclass{
|
||||
font-family: Helvetica, sans-serif;
|
||||
font-size:25;
|
||||
font-weight: normal;
|
||||
color: blue;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<h3 style="text-align: center; color: green">
|
||||
<span th:text="'Welcome to ' + ${to} + '!'"></span>
|
||||
</h3>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,3 @@
|
||||
Test
|
||||
Text
|
||||
Test TEST
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.pdf.base64;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class EncodeDecodeUnitTest {
|
||||
|
||||
private static final String IN_FILE = "src/test/resources/input.pdf";
|
||||
private static final String OUT_FILE = "src/test/resources/output.pdf";
|
||||
private static byte[] inFileBytes;
|
||||
|
||||
@BeforeClass
|
||||
public static void fileToByteArray() throws IOException {
|
||||
inFileBytes = Files.readAllBytes(Paths.get(IN_FILE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaBase64_whenEncoded_thenDecodedOK() throws IOException {
|
||||
|
||||
byte[] encoded = java.util.Base64.getEncoder().encode(inFileBytes);
|
||||
|
||||
byte[] decoded = java.util.Base64.getDecoder().decode(encoded);
|
||||
|
||||
writeToFile(OUT_FILE, decoded);
|
||||
|
||||
assertNotEquals(encoded.length, decoded.length);
|
||||
assertEquals(inFileBytes.length, decoded.length);
|
||||
|
||||
assertArrayEquals(decoded, inFileBytes);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaBase64_whenEncodedStream_thenDecodedStreamOK() throws IOException {
|
||||
|
||||
try (OutputStream os = java.util.Base64.getEncoder().wrap(new FileOutputStream(OUT_FILE));
|
||||
FileInputStream fis = new FileInputStream(IN_FILE)) {
|
||||
byte[] bytes = new byte[1024];
|
||||
int read;
|
||||
while ((read = fis.read(bytes)) > -1) {
|
||||
os.write(bytes, 0, read);
|
||||
}
|
||||
}
|
||||
|
||||
byte[] encoded = java.util.Base64.getEncoder().encode(inFileBytes);
|
||||
byte[] encodedOnDisk = Files.readAllBytes(Paths.get(OUT_FILE));
|
||||
assertArrayEquals(encoded, encodedOnDisk);
|
||||
|
||||
byte[] decoded = java.util.Base64.getDecoder().decode(encoded);
|
||||
byte[] decodedOnDisk = java.util.Base64.getDecoder().decode(encodedOnDisk);
|
||||
assertArrayEquals(decoded, decodedOnDisk);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenApacheCommons_givenJavaBase64_whenEncoded_thenDecodedOK() throws IOException {
|
||||
|
||||
byte[] encoded = org.apache.commons.codec.binary.Base64.encodeBase64(inFileBytes);
|
||||
|
||||
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
|
||||
|
||||
writeToFile(OUT_FILE, decoded);
|
||||
|
||||
assertNotEquals(encoded.length, decoded.length);
|
||||
assertEquals(inFileBytes.length, decoded.length);
|
||||
|
||||
assertArrayEquals(decoded, inFileBytes);
|
||||
}
|
||||
|
||||
private void writeToFile(String fileName, byte[] bytes) throws IOException {
|
||||
FileOutputStream fos = new FileOutputStream(fileName);
|
||||
fos.write(bytes);
|
||||
fos.flush();
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.pdfreadertest;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
|
||||
|
||||
class ReadPdfFileUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSamplePdf_whenUsingApachePdfBox_thenCompareOutput() throws IOException {
|
||||
String expectedText = "Hello World!\n";
|
||||
|
||||
File file = new File("sample.pdf");
|
||||
PDDocument document = PDDocument.load(file);
|
||||
|
||||
PDFTextStripper stripper = new PDFTextStripper();
|
||||
|
||||
String text = stripper.getText(document);
|
||||
|
||||
document.close();
|
||||
|
||||
assertEquals(expectedText, text);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSamplePdf_whenUsingiTextPdf_thenCompareOutput() throws IOException {
|
||||
String expectedText = "Hello World!";
|
||||
|
||||
PdfReader reader = new PdfReader("sample.pdf");
|
||||
int pages = reader.getNumberOfPages();
|
||||
StringBuilder text = new StringBuilder();
|
||||
|
||||
for (int i = 1; i <= pages; i++) {
|
||||
|
||||
text.append(PdfTextExtractor.getTextFromPage(reader, i));
|
||||
|
||||
}
|
||||
reader.close();
|
||||
assertEquals(expectedText, text.toString());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.pdfthymeleaf;
|
||||
|
||||
import com.lowagie.text.DocumentException;
|
||||
import org.junit.Test;
|
||||
import org.thymeleaf.TemplateEngine;
|
||||
import org.thymeleaf.context.Context;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
import org.xhtmlrenderer.pdf.ITextRenderer;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PDFThymeleafUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenThymeleafTemplate_whenParsedAndRenderedToPDF_thenItShouldNotBeEmpty() throws DocumentException, IOException {
|
||||
String html = parseThymeleafTemplate();
|
||||
|
||||
ByteArrayOutputStream outputStream = generatePdfOutputStreamFromHtml(html);
|
||||
|
||||
assertTrue(outputStream.size() > 0);
|
||||
}
|
||||
|
||||
private ByteArrayOutputStream generatePdfOutputStreamFromHtml(String html) throws IOException, DocumentException {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
|
||||
ITextRenderer renderer = new ITextRenderer();
|
||||
renderer.setDocumentFromString(html);
|
||||
renderer.layout();
|
||||
renderer.createPDF(outputStream);
|
||||
|
||||
outputStream.close();
|
||||
return outputStream;
|
||||
}
|
||||
|
||||
private String parseThymeleafTemplate() {
|
||||
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
|
||||
templateResolver.setSuffix(".html");
|
||||
templateResolver.setTemplateMode(TemplateMode.HTML);
|
||||
|
||||
TemplateEngine templateEngine = new TemplateEngine();
|
||||
templateEngine.setTemplateResolver(templateResolver);
|
||||
|
||||
Context context = new Context();
|
||||
context.setVariable("to", "Baeldung.com");
|
||||
|
||||
return templateEngine.process("thymeleaf_template", context);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user