Currently i am using following code to generate PDF in a JSP file:
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename=reports.pdf");
Document document = new Document();
document.setPageSize(PageSize.A1);
PdfWriter writer = null;
writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
ByteArrayInputStream bis = new ByteArrayInputStream(htmlSource.toString().getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis);
document.close();
With this am able to generate PDF.
But i would like to add CSS file while generating PDF.
Please Help me...
i am not sure in java how can you use but in c# you can add external style sheet code or syntax by this code:-
StyleSheet css = new StyleSheet();
css.LoadTagStyle("body", "face", "Garamond");
css.LoadTagStyle("body", "encoding", "Identity-H");
css.LoadTagStyle("body", "size", "12pt");
may be this helps you
Regards,
vinit
Please take a look at the ParseHtmlTable1 example. In this example, we have HTML stored in a StringBuilder object and some CSS stored in a String. In my example, I convert the sb object and the CSS object to an InputStream. If you have files with the HTML and the CSS, you could easily use a FileInputStream.
Once you have an InputStream for the HTML and the CSS, you can use this code:
// CSS
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(CSS.getBytes()));
cssResolver.addCss(cssFile);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
// Pipelines
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.parse(new ByteArrayInputStream(sb.toString().getBytes()));
Or, if you don't like all that code:
ByteArrayInputStream bis = new ByteArrayInputStream(htmlSource.toString().getBytes());
ByteArrayInputStream cis = new ByteArrayInputStream(cssSource.toString().getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis, cis);
You may try this code reference.
$html .= '<style>'.file_get_contents(_BASE_PATH.'stylesheet.css').'</style>';
Change content type to
response.setContentType("application/pdf");
Related
I am trying to convert some html content to a pdf using the itext PdfWriter, like this:
Document document = new Document();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
XMLWorkerHelper.getInstance().parseXHtml(writer, document, stream, Charset.forName("UTF-8"));
document.close();
but the ă ș ț charaters are missing from the generated pdf. I have tried setting the encoding or the font, but with no luck. What I tried was to use a font provider and set it as a param to the parseXHtml method.
I set the encoding, but nothing changed.
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider();
fontProvider.setUseUnicode(true);
fontProvider.defaultEncoding = BaseFont.CP1257;
I also tried setting the font, but it was not applied to the pdf.
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.register(PATH_TO_TTF_FONT_FILE_HOSTED_ON_S3);
And then set the param for parseXHtml.
XMLWorkerHelper.getInstance().parseXHtml(writer, document, stream, Charset.forName("UTF-8"), fontProvider);
Is there any way I could use the PdfWriter to convert all characters correctly from html to pdf?
If we have string with a content of a html page, how can we convert it to a InputStream made after transform this string to a pdf document?
I'm trying to use iText with XMLWorkerHelper, and this following code works, but the problem is I don't want the output on a file. I have tried several variations in order to get the result on a InputStream that I could convert to a Primefaces StreamedContent but no success. How we can do it?
Is there another technique that we can use to solve this problem?
The motivation to this is use xhtml files wich is already rendered and output it as a pdf to be downloaded by the user.
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("results/loremipsum.pdf"));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream("/html/loremipsum.html"));
document.close();
If you need an InputStream from which some other code can read the PDF your code produces, you can simply create the PDF using a byte array output stream and thereafter wrap the byte array from that stream in a byte array input stream:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("/html/loremipsum.html"));
document.close();
ByteArrayInputStream pdfInputStream = new ByteArrayInputStream(baos.toByteArray());
You can optimize this a bit by creating and processing the PDF in different threads and using a PipedOutputStream and a PipedInputStream instead.
I am trying to convert html file into pdf using iText lib(4.2.0). But the problem is it's not printing all the html content to pdf, its only partially printing some data. Here is the code to convert html to pdf.
InputStream il = new FileInputStream("/tmp/test.html");
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/tmp/pdf.pdf"));
writer.setInitialLeading(12.5f);
// step 3
document.open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
// CSS
CSSResolver cssResolver = new StyleAttrCSSResolver();
InputStream csspathtest =new FileInputStream("/tmp/test.css");
CssFile cssfiletest = XMLWorkerHelper.getCSS(csspathtest);
cssResolver.addCss(cssfiletest);
Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlContext,
new PdfWriterPipeline(
document, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(worker);
p.parse(il);
// step
document.close();
Here is the sample html file http://codepaste.net/65kmhp
How can i create a pdf into gcs, and also insert some data?
This is my code:
GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
.initialRetryDelayMillis(10)
.retryMaxAttempts(10)
.totalRetryPeriodMillis(15000)
.build());
GcsFilename filename = new GcsFilename("areteaics", "test.pdf");
GcsFileOptions options = new GcsFileOptions.Builder().mimeType("application/pdf").build();
GcsOutputChannel writeChannel = gcsService.createOrReplace(filename,options);
PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel, "UTF8"));
//out.println("The woods are lovely dark and deep.");
//out.println("But I have promises to keep.");
//out.flush();
writeChannel.waitForOutstandingWrites();
//writeChannel.write(ByteBuffer.wrap("And miles to go before I sleep.".getBytes()));
writeChannel.close();
It doesn't look like you are creating a pdf formatted file (you're just making a file with the extension pdf). You need to use a library like itext to create the pdf file and then write it to cloudstorage.
e.g using itext to write to outputstream src:
Document document = new Document();
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("This is a paragraph"));
document.close();
You'd need to modify the above code to write to gcs (instead of response outputstream).
I want to convert my XHTML text to a PDF. I converted it to FileOutputStream but I ca'nt find a way to pass it as an input to the ITextRenderer. Is that possible, and how?
the code :
String finalXhtml=xhtmlparser(xmlText);
ByteArrayInputStream finalXhtmlStream = new ByteArrayInputStream(finalXhtml.getBytes());
String HTML_TO_PDF = "ConvertedFile.pdf";
OutputStream os = new FileOutputStream(HTML_TO_PDF);
ITextRenderer renderer = new ITextRenderer();
// renderer.loadDocument(finalXhtmlStream); i can pass a file here can i pass an input or output stream ?
renderer.layout();
renderer.createPDF(os) ;
os.close();
System.out.println("done.");
note: I can pass a file to the ITextRenderer as following:
String File_To_Convert = "report.xhtml";
String url = new File(File_To_Convert).toURI().toURL().toString();
String HTML_TO_PDF = "ConvertedFile.pdf";
OutputStream os = new FileOutputStream(HTML_TO_PDF);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
System.out.println("done.");
please let me know if I have to provide more details.
I am using following code to export HTML data to PDF with following code:
renderer.setDocumentFromString(htmls.toString());
renderer.layout();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + ".pdf\"");
renderer.createPDF(outputStream);
renderer.createPDF(fos);
Now here I am using inline CSS to generate PDF using style but is there any option that I can use setDocumentFromString() function by loading external CSS.
I am assuming you are using Flying Saucer. ITextRenderer has a method that does something similar:
public void setDocumentFromString(String content) {
InputSource is = new InputSource(new BufferedReader(new StringReader(content)));
Document dom = XMLResource.load(is).getDocument();
setDocument(dom, null);
}
Adapting your code, what you'd want would look something like this:
String finalXhtml=xhtmlparser(xmlText);
ByteArrayInputStream finalXhtmlStream = new ByteArrayInputStream(finalXhtml.getBytes());
String HTML_TO_PDF = "ConvertedFile.pdf";
OutputStream os = new FileOutputStream(HTML_TO_PDF);
Document document = XMLResource.load(finalXhtmlStream).getDocument();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(document, null);
renderer.layout();
renderer.createPDF(os) ;
os.close();
of course you could also do this and skip the inputstream all together:
renderer.setDocumentFromString(finalXhtml);