Tuesday, May 3, 2016

How to convert Html to Pdf using itextpdf

In Below code you can can convert pure html to PDF using Itextpdf.

You can specify custom header ,footer and page end content with page no.

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.zul.Filedownload;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.codec.Base64;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.AbstractImageProvider;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

public class PDFUtil{
static final Logger LOG = LoggerFactory.getLogger(PDFUtil.class);
static final String ENDTEXT = "<div><div align=\"" + "center" + "\""
+ "><hr/><b>PROHIBITION ON REDISCLOSURE OF CONFIDENTIAL INFORMATION</b></div> This notice accompanies a disclosure of information concerning an individual in alcohol/drug treatment, made to you with the consent of such individual. </div>";

public void exportPDF(String src, String fileName) {
String prci = FHSessionUtil.getOptionValueByKey("prci");
if (prci != null) {
src = src + prci;
} else {
src = src + ENDTEXT;
}
try {
InputStream is = new ByteArrayInputStream(src.getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document(PageSize.A3);
PdfWriter writer = PdfWriter.getInstance(document, baos);
writer.setInitialLeading(12.5f);
MyFooter event = new MyFooter();
writer.setPageEvent(event);
writer.setStrictImageSequence(true);
document.open();
document.addTitle(fileName);
document.addCreationDate();
document.addCreator("By Himanshu");
document.addAuthor(FHSessionUtil.getCurrentUser().getFirstName());
document.setJavaScript_onLoad(FHSessionUtil.getAppResourcePath() + "/resources/js/bootstrap.min.js");
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
htmlContext.setImageProvider(new Base64ImageProvider());

Pipeline<?> pipeline = new CssResolverPipeline(getCSSResolver(), new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(worker);
p.parse(is);
document.close();

Filedownload.save(baos.toByteArray(), "application/pdf", fileName + ".pdf");
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
} catch (DocumentException e) {
// e.printStackTrace();
}

}

class MyFooter extends PdfPageEventHelper {
Font ffont = new Font(Font.FontFamily.UNDEFINED, 15, Font.ITALIC);

@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
// Phrase header = new Phrase(FHSessionUtil.getOptionValueByKey("title"), ffont);
Phrase footer = new Phrase(FHSessionUtil.getOptionValueByKey("title"), ffont);
Phrase pageNo = new Phrase(String.valueOf(writer.getPageNumber()), ffont);

// ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header, (document.right() - document.left()) / 2 + document.leftMargin(),
// document.top() + 10, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.right() - document.left()) / 2 + document.leftMargin(),
document.bottom() - 10, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, pageNo, (document.right() - 10), document.bottom() - 10, 0);
}

@Override
public void onCloseDocument(PdfWriter writer, Document document) {
LOG.info("#######################");
Phrase footer = new Phrase(FHSessionUtil.getOptionValueByKey("title") + "", ffont);

PdfContentByte cb = writer.getDirectContent();

ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.right() - 10), document.bottom() - 10, 0);
}

}

class Base64ImageProvider extends AbstractImageProvider {

@Override
public Image retrieve(String src) {
int pos = src.indexOf("base64,");
try {
if (src.startsWith("data") && pos > 0) {
byte[] img = Base64.decode(src.substring(pos + 7));
return Image.getInstance(img);
} else {
return Image.getInstance(src);
}
} catch (BadElementException ex) {
return null;
} catch (IOException ex) {
return null;
}
}

@Override
public String getImageRootPath() {
return null;
}
}

// private String getHtmlString(String src) {
// StringBuilder sb = new StringBuilder();
// sb.append("<html><head><title></title></head><body >");
// sb.append(src);
// sb.append("</body></html>");
// return sb.toString();
// }

private CSSResolver getCSSResolver() {
CSSResolver cssResolver = new StyleAttrCSSResolver();
String resourcePath = FHSessionUtil.getAppResourcePath();
for (String cssFile : getCSSFiles()) {
InputStream fis;
try {
fis = new URL(resourcePath + cssFile).openStream();
CssFile cssfiletest = XMLWorkerHelper.getCSS(fis);
cssResolver.addCss(cssfiletest);
} catch (IOException e) {

}
}
return cssResolver;
}

private List<String> getCSSFiles() {
List<String> cssFiles = new ArrayList<>();
cssFiles.add("/resources/css/bootstrap.min.css");
cssFiles.add("/zkau/web/ccf53197/zul/css/zk.wcs");
cssFiles.add("/resources/css/plugins/iCheck/custom.css");
cssFiles.add("/resources/font-awesome/css/font-awesome.css");
cssFiles.add("/resources/css/animate.css");
cssFiles.add("/resources/css/plugins/toastr/toastr.min.css");
cssFiles.add("/resources/css/plugins/switch/bootstrap-switch.css");
cssFiles.add("/resources/css/mystyle.css");
cssFiles.add("/resources/css/style.css");
return cssFiles;
}


}

No comments:

Post a Comment

How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...