itextpdf generates blurry pictures - itext

I am using itextpdf html2pdf tool to implement freemarker template to generate pdf
Refer to the official documentation link:
https://kb.itextpdf.com/home/it7kb/ebooks/itext-7-converting-html-to-pdf-with-pdfhtml/chapter-7-frequently-asked-questions-about-pdfhtml/can-pdfhtml-render-base64-images-to-pdf
The front end uses echarts to convert the image to base64.
The picture can be displayed clearly on the browser, but after the pdf is generated, the picture becomes blurry.
Refer to html and pdf image comparison:
html pdf
public static void main(String[] args) throws Exception{
File file = FileUtil.newFile("D:/test.html");
BufferedOutputStream outputStream = FileUtil.getOutputStream("D:/test.pdf");
BufferedInputStream inputStream = FileUtil.getInputStream(file);
ConverterProperties converterProperties=new ConverterProperties();
FontProvider fontProvider=new DefaultFontProvider();
FontProgram fontProgram = FontProgramFactory.createFont(Constant.CONFIG_PATH+File.separator+"simsun.ttc,1");
fontProvider.addFont(fontProgram);
MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.SCREEN);
mediaDeviceDescription.setResolution(2000f);
converterProperties.setFontProvider(fontProvider);
converterProperties.setMediaDeviceDescription(mediaDeviceDescription);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outputStream));
pdfDoc.setDefaultPageSize(new PageSize(1000,1700));
HtmlConverter.convertToPdf(inputStream,pdfDoc,converterProperties);
}

Related

Image scrambled when embedded into pdf using iTextSharp

I'm having an issue when attempting to create a PDF with an image using iTextSharp. I'm adding the image to the top of the PDF like a masthead and then the rest of the PDF is HTML. The PDF generates fine and displays correctly when viewed in Edge, Chrome and Firefox. But, if you open it in IE or in Adobe Reader, the masthead is completely scrambled. The rest of the PDF (the HTML content) generates as expected in all browsers and programs. I've googled for days now trying to discover if anyone else has had this issue, but all I can find is text being garbled, not images. Below is the code I'm using to generate the image. Any ideas?
using (var document = new Document(PageSize.A4, 10f, 10f, 10f, 10f))
{
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Content/Images/kfa_masthead.jpg"));
using (var ms = new MemoryStream())
{
image.Left = 10f;
image.Top = image.Height;
image.ScaleAbsolute(560f, 58f);
using (var writer = PdfWriter.GetInstance(document, ms))
{
document.Open();
writer.CloseStream = false;
//Add the masthead
document.Add(image);
//Add the report information
var html = CreateTable(profile);
using (var xHtml = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, xHtml);
}
document.CloseDocument();
document.Close();
}
return ms.ToArray();
}
}

converting html to pdf using itext the image result in pdf is small unlike the original

As a beginner in android, I was having a hard time converting html to pdf, every time I convert the html to pdf the result image inside the pdf file is small. How can I solve this problem? This code I am using to convert the html:
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
InputStream htmlPath = getAssets().open(filename + ".html");
XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
helper.parseXHtml(writer, document, htmlPath);
document.close();
writer.close();
this is the result:

Html to PDF , text inside <pre> not coming good in PDF

I am trying to convert html to pdf with iText API(itextpdf.5.5.7.jar, xmlworker 5.5.7.jar), everything is good except the text inside the pre tag.
In html the text inside the pre is good but in PDF the formatting is totally gone and simply coming in normal lines without formatting. I checked the blogs but I did not find correct answer.
Please find the screen shots for HTML and PDF.
HTML screen:
PDF screen:
this is my code
String pdfFileName="C:\test.pdf";
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(pdfFileName));
writer.setInitialLeading(12.5f);
document.open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
CSSResolver cssResolver = XMLWorkerHelper.getInstance()
.getDefaultCssResolver(true);
Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlContext, new PdfWriterPipeline(document,
writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(worker);
File input = new File(completeHtmlFilePath);
p.parse(new InputStreamReader(new FileInputStream(input), "UTF-8"));
document.close();
return pdfFileNameWithPath;

Save JavaFX ScrollPane content to PDF file

I'm using the below code to save the content of a ScrollPane in my JavaFx Application to a PDF file.
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
File pdfFile = fileChooser.showSaveDialog(primaryStage);
try {
BufferedImage bufImage = SwingFXUtils.fromFXImage(scrollPane.snapshot(new SnapshotParameters(), null), null);
FileOutputStream out = new FileOutputStream(new File("../temp.jpg"));
javax.imageio.ImageIO.write(bufImage, "jpg", out);
out.flush();
out.close();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance("../temp.jpg");
Document doc = new Document(new com.itextpdf.text.Rectangle(image.getScaledWidth(), image.getScaledHeight()));
FileOutputStream fos = new FileOutputStream(pdfFile);
PdfWriter.getInstance(doc, fos);
doc.open();
doc.newPage();
image.setAbsolutePosition(0, 0);
doc.add(image);
fos.flush();
doc.close();
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
In the scrollpane, I have a very long VBox which contains almost 40-50 labels. So, this code initially saves it to a jpg file and then adds it to a pdf file.
When the temp.jpg is created initially, due to its length, the jpg file looks very thin. It should be zoomed to see the actual content.
When the pdf file is written, it was blank except that it was lengthy as it would have been when the jpg is really converted to a PDF file.
Can anyone help me fix this ? to take the snapshot of the ScrollPane to PDF with its actual size/scale ?
I have first scaled the image and then created document with scaled PageSize. This fixed the issue
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance("../temp.jpg");
image.scalePercent(1);
Document doc = new Document(new com.itextpdf.text.Rectangle(image.getScaledWidth(), image.getScaledHeight()));
doc.open();
doc.add(image);

iText PDF image partially displayed

The image is not displayed correctly in my PDF (iText) when I access thru my Java code.
It displays partially with the first half of the image displaying properly and the remaining half displays with a lot of lines on top of the image. (the images seems to be downloading very slow when other text show up fast).
I use iTextPdf version 5.4.0 jar file and I access the image thru URL (get the image URL)
in my java code.
Please let me know why this happens. If you need any additional info please let me know and I can provide.
Thanks in advance for any help.
Im also faced Same issue, later we solved. Please find the below code, hope it will help for you.
HTML FILE
<html>
<body>
<font color="green">Test</font><br/>
<table>
<tr><td><img src="Desert.jpg" height="300" width="300"/></td></tr>
</table>
</body>
</html>
Java File
class PageWithRectangle extends PdfPageEventHelper
{
public void onEndPage(PdfWriter writer, Document document)
{
PdfContentByte cb = writer.getDirectContent();
Rectangle pageSize = writer.getPageSize();
cb.rectangle(pageSize.getLeft() + 3, pageSize.getBottom() + 3,
pageSize.getWidth() - 6, pageSize.getHeight() - 6);
cb.stroke();
}
}
public class pdfTest {
private static String getUrlSource(String url) throws IOException {
URL webpage = new URL(url);
URLConnection yc = webpage.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
{
a.append(inputLine);
System.out.println(inputLine);
}
in.close();
return a.toString();
}
public static void main(String[] args) {
try {
File baseDir = new File(".");
File outDir = new File(baseDir, "out");
outDir.mkdirs();
String k = getUrlSource("file:\\C:\\test.html");
OutputStream file = new FileOutputStream(new File(outDir+"/Test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
writer.setPageEvent(new PageWithRectangle());
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(k));
document.close();
file.close();
System.out.println("\nSuccess");
} catch (Exception e) {
e.printStackTrace();
}
}
}
My Old HTML Code(Gave wrong pdf while generate through java)
<html>
<body>
<font color="green">Test</font><br/>
<img src="Desert.jpg" height="300" width="300"/>
</body>
</html>
Solution : give image tag under table tag
Regards,
Praveen
I also have experienced this issues using iText 5.5.5 and found the issue affecting GIF's with alpha channel set. Either remove the alpha or try saving as a jpg. This worked for me.