white-space:nowrap does not work properly with Flying Saucer - java

I am using Flying Saucer to convert HTML documents to PDF. But there is a problem when I use <span style="white-space:nowrap">
Generally white-space:nowrap works fine. But when the span is near the right-margin of the document, it gets trimmed.
For example:
This html This is fine. <span style="white-space:nowrap">This is a test</span> gets converted to pdf like this:
which is perfect.
But when I use This is fine. This is also fine. <span style="white-space:nowrap">This is a test</span>, it gets converted to
Notice that part of span is trimmed because of right-margin.
What I expect is:
i.e. I expect the span to move to next line.
The code I am using to convert to pdf is:
String inputFile = "test.html";
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = "firstdoc.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();

Related

Convert docx to pdf using Apache POI

The task is this, you need to create a printable form, replace the fields with the necessary data and convert to pdf format. Replacing text and saving in docx format is correct.
But when I run:
PdfConverter.getInstance().convert(document, outputStream, pdfOptions);
The fields that have been replaced are missing in the pdf file. The fields in the form are entered in the form for tex (figure), you can see it in the photo.
If you insert into plain text, then the replacement is correct. I think that you need to somehow configure PdfOptions, but so far there are no options for how to do it ...
If someone had such a problem and has suggestions on what to try to do, I will be glad for help))
The code that converts the finished form:
`InputStream inputStream = ByteSource.wrap(printFileDTO.getContent()).openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfOptions pdfOptions = PdfOptions.create();
pdfOptions.fontProvider((familyName, encoding, size, style, color) -> {
try {
BaseFont baseFont =
BaseFont.createFont(TNR, encoding, BaseFont.EMBEDDED);
return new Font(baseFont, size, style, color);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
XWPFDocument document = new XWPFDocument(inputStream);
PdfConverter.getInstance().convert(document, outputStream, pdfOptions);`
Versions:
<apache.poi>5.2.3</apache.poi> <poi.ooxml.version>5.2.3</poi.ooxml.version> <poi.scratchpad.version>5.2.3</poi.scratchpad.version> <opensagres.xdocreport.version>2.0.3</opensagres.xdocreport.version>
Updated to the latest to try, but it did not change anything
Piece of completed form:
enter image description here

Barcode in PDF not displaying in FireFox [duplicate]

I am running into strange issue with generated pdf's from iText7. The generated pdf's are opening properly in Adobe reader and Chrome browser. But the same pdf is opening partially in the Firefox browser. I am getting the below message in Firefox. The strange thing is other pdf, which are not generated via iText are properly rendering in firefox.
Java code
public static byte[] createPdf(List<String> htmlPages, PageSize pageSize, boolean rotate) throws IOException {
ConverterProperties properties = new ConverterProperties();
// Register classpath protocol handler to be able to load HTML resources from class patch
org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.register();
properties.setBaseUri("classpath:/");
// properties.setBaseUri(baseUri);
FontProvider fontProvider = new DefaultFontProvider(true,false,false);
properties.setFontProvider(fontProvider);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfDocument pdf = new PdfDocument(new PdfWriter(byteArrayOutputStream));
PdfMerger merger = new PdfMerger(pdf);
for (String htmlPage : htmlPages) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument temp = new PdfDocument(new PdfWriter(baos));
if(rotate) {
temp.setDefaultPageSize(pageSize.rotate()); /** Page Size and Orientation */
} else {
temp.setDefaultPageSize(pageSize); /** Page Size and Orientation */
}
HtmlConverter.convertToPdf(htmlPage, temp, properties);
temp = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
merger.merge(temp, 1, temp.getNumberOfPages());
temp.close();
}
pdf.close();
byteArrayOutputStream.flush(); // Tried this
byteArrayOutputStream.close(); // Tried this
byte[] byteArray = byteArrayOutputStream.toByteArray();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try (FileOutputStream fileOuputStream = new FileOutputStream("D:\\Labels\\Label_"+timestamp.getTime()+".pdf")){
fileOuputStream.write(byteArray);
}
return byteArray;
}
Thanks in advance.
Edit 1:
You can find pdf and html/css for reproducing issue here.
When you embedded the images into your html using base64 URIs, something weird happened to the image of the barcode: Instead of the 205×59 bitmap image in labelData/barcode.png you embedded a 39578×44 image! (Yes, an image nearly a thousand times wider than high...)
The iText HtmlConverter embedded that image just fine but apparently Firefox has issues displaying an image with those dimensions even though (or probably because?) it is transformed into the desired dimensions (about four times wider than high) on the label. At least my Firefox installation stops drawing label contents right here. (Beware, the order of drawing in the PDF content is not identical to the of the HTML elements; in particular in the PDF the number 3232000... is drawn right before the barcode, not afterwards!)
On Firefox:
On Acrobat Reader:
Thus, you may want to check the transformation of the bar code image to the base64 image URI in your HTML file.

Apache PdfBox Rotate Crop Box Only Not Text

I am trying to go from text to pdf but have only one of the pages rotated 90 degress. Main reason is that some of my text documents are a bit too large and need to be in landscape to look normal. I have tried a few things but it seems like everything rotates the text too. Is there an easy way to rotate the pdf to landscape but keep the text the same rotation?
OutputStream outputStream = response.getOutputStream();
PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
Map<String, Documents> documents = getDocuments(user, documentReports);
try (PDDocument documentToPrint = new PDDocument()){
for(Document doc : documentReports){
TextToPDF textToPDF = new TextToPDF();
textToPDF.setFont(PDType1Font.COURIER);
textToPDF.setFontSize(8);
Document documentReport = documents.get(doc.getId());
try(PDDocument pdDocument = textToPDF.createPDFFromText(new InputStreamReader(new ByteArrayInputStream(documentReport.getReportText().getBytes())))) {
pdfMergerUtility.appendDocument(documentToPrint, pdDocument);
}
}
pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
LocalDateTime localUtcTime = Java8TimeUtil.getCurrentUtcTime();
documentToPrint.getDocumentInformation().setTitle(localUtcTime.toString());
response.setHeader("Content-Disposition", "inline; filename=" + localUtcTime + ".pdf");
response.setContentType("application/pdf");
documentToPrint.save(outputStream);
}
So this might not work for everyone but I figured it out for my specific requirement. TextToPDF has a method called setLandscape before creating the pdf from text. textToPDF.setLandscape(true);

Create a New Page During Text to PDF conversion Using Itext

I am converting a text file to PDF using iText. The conversion works fine but I need that during conversion if the BufferedReader encounters a certain text, a new PDF Page is Started. This is what I have tried But A new Page is not started when that Text is encountered. My Sample code is as Below(Just the relevant part).
Document output = new Document(PageSize.B3);
FileInputStream fs = new FileInputStream("C:/ABC Statements final/File.TXT");
FileOutputStream file = new FileOutputStream(new File("C:/Pdf Statements/File.PDF"));
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
PdfWriter writer = PdfWriter.getInstance(output, file);
output.open();
writer.open();
.............................
String pageend = "Page Total";
String trimmedend = br.readLine().trim();
if (trimmedend.startsWith(pageend)) {
output.newPage();
}
Maybe you need to change your if-statement to something like this:
String pageend = "page total";
...
if (trimmedend.toLowerCase().contains(pageend)) {
...
}
This way, you avoid case-sensitivity and you avoid the problem of having characters that aren't considered being white space before "page total". Of course: this is just an educated guess. I don't know what your original data stream looks like.

iText style parsing HTML to PDF

I've a problem with iText.
I've followed this link: How to export html page to pdf format?
My snippet:
String str = "<html><head><body><div style=\"width:100%;height:100%;\"><h3 style=\"margin-left:5px;margin-top:40px\">First</h3><div style=\"margin-left:15px;margin-top:15px\"><title></title><p>sdasdasd shshshshdffgdfgd</p></div><h3 style=\"margin-left:5px;margin-top:40px\">The dream</h3><div style=\"margin-left:15px;margin-top:15px\"></div></div></body></head></html>";
String fileNameWithPath = "/Users/cecco/Desktop/pdf2.pdf";
com.itextpdf.text.Document document =
new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4);
FileOutputStream fos = new FileOutputStream(fileNameWithPath);
com.itextpdf.text.pdf.PdfWriter pdfWriter =
com.itextpdf.text.pdf.PdfWriter.getInstance(document, fos);
document.open();
document.addAuthor("Myself");
document.addSubject("My Subject");
document.addCreationDate();
document.addTitle("My Title");
com.itextpdf.text.html.simpleparser.HTMLWorker htmlWorker =
new com.itextpdf.text.html.simpleparser.HTMLWorker(document);
htmlWorker.parse(new StringReader(str.toString()));
document.close();
fos.close();
and work fine.
But tag style into h3 and div aren't considered.
But if I copy my html into http://htmledit.squarefree.com/ all is correct.
How can I solve this problem?
iText isn't the best Html Parser, but you can use Flying-Saucer for this. Flying-Saucer is build on top of iText but has a capable Xml / (X)Html parser. Short: Flying Saucer is perfect if you want html -> Pdf.
Here's how to generate the pdf from your string:
/*
* Note: i filled something in the title-tag and fixed the head tag (the whole body-tag was in the head)
*/
String str = "<html><head></head><body><div style=\"width:100%;height:100%;\"><h3 style=\"margin-left:5px;margin-top:40px\">First</h3><div style=\"margin-left:15px;margin-top:15px\"><title>t</title><p>sdasdasd shshshshdffgdfgd</p></div><h3 style=\"margin-left:5px;margin-top:40px\">The dream</h3><div style=\"margin-left:15px;margin-top:15px\"></div></div></body></html>";
OutputStream os = new FileOutputStream(new File("example.pdf"));
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(str);
renderer.layout();
renderer.createPDF(os);
os.close();
But: FS supports only valid Html / Xhtml / xml, so make shure it is.

Categories

Resources