I am converting html data into pdf,but I got white space where some large data will insert, I'd like to trim off the whitespace for following data
note: header is coming from jasper report
'Document document = new Document(PageSize.A4, 40, 72, getMargins(1),20);`
document.setMarginMirroringTopBottom(true);`
String path = dao.gettomcatserverPath1() + "webapps/wordimages/disch" +patid+ ".pdf";`
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
`String html = "";
List list1 = dao.executeQuery("select wordole from ip.dischargetemplate where patid='"+patid+"'");
html = ((Map)list1.get(0)).get("WORDOLE").toString();
InputStream _ishtml = new ByteArrayInputStream(html.getBytes());
HeaderFooter event = new HeaderFooter();`
writer.setPageEvent(event);`
writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));`
document.open();`
Font font = FontFactory.getFont("Times-Roman");
XMLWorkerHelper.getInstance().parseXHtml(writer, document, _ishtml);`
document.close();`
Related
I created a PDF file in Java using OpenPDF and inserted a paragraph. The problem is that I want to place it in the middle, not on the left. How can this be done?
Second question: How can I place a word with specific formatting in the test?
For example: "Hello and welcome" (welcome should be bold)
This is my code:
Document document = new Document();
String PDFPath = "output.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
Font font_bold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD, Color.BLACK);
Font font_normal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL, Color.BLACK);
Paragraph p1 = new Paragraph("Ordonnance", font_bold);
document.open();
document.add(p1);
document.close();
You need to define the alignment if you want to have the paragraph centred:
p1.setAlignment(Element.ALIGN_CENTER);
To apply formatting to some parts of the text, you can divide it into several chunks. A Chunk in OpenPDF is a string with a certain Font. Instead of adding a String (unformatted) to the paragraph, you add a Chunk-object like new Chunk("Hello and ", fontNormal) which defines the text and the font to be used.
Here is the code for what you want to do according to the question:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
document.open();
Font fontNormal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL);
Font fontBold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD);
Paragraph p1 = new Paragraph();
p1.setAlignment(Element.ALIGN_CENTER);
p1.add(new Chunk("Hello and ", fontNormal));
p1.add(new Chunk("welcome", fontBold));
document.add(p1);
document.close();
The result looks like this:
Your first line had some weird declaration, but this should work:
Document document = new Document();
String PDFPath = "D:\\test.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
Font font_bold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD, Color.BLACK);
Font font_normal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL, Color.BLACK);
Paragraph p1 = new Paragraph("Ordonnance", font_bold);
p1.setAlignment(Element.ALIGN_CENTER);
document.open();
document.add(p1);
document.close();
You just have to set the alignment of the paragraph
i am trying to create pdf using pdfbox. i am storing EditText data as html in Sqlite DB.
now i am retrieving data from sqliteDB and creating pdf of that. this data is having marathi language as well as english language.
i am using NotoSerifDevanagari-Bold font and have added it to assets folder. from there i am accessing this font into code. but i am getting error. please find my code and error below.
AssetManager assetManager;
PDFBoxResourceLoader.init(getApplicationContext());
File FilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
assetManager = getAssets();
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDFont font = PDType0Font.load(document, assetManager.open("notoserifdevanagaribold.ttf"));
PDPageContentStream contentStream;
// Define a content stream for adding to the PDF
contentStream = new PDPageContentStream(document, page);
Cursor data = mDatabaseHelper.getDataByDeckname(deckname);
StringBuilder builder=new StringBuilder();
while (data.moveToNext()) {
String front_page_desc = data.getString(3);
String back_page_desc = data.getString(4);
contentStream.beginText();
contentStream.setNonStrokingColor(15, 38, 192);
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(100, 700);
contentStream.showText(Html.fromHtml(front_page_desc).toString());
contentStream.endText();
contentStream.beginText();
contentStream.setNonStrokingColor(15, 38, 192);
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(100, 700);
contentStream.showText(Html.fromHtml(back_page_desc).toString());
contentStream.endText();
}
contentStream.close();
String path = FilePath.getAbsolutePath() + "/temp.pdf";
document.save(path);
document.close();
ERROR
W/System.err: java.lang.IllegalArgumentException: No glyph for U+000A in font NotoSerifDevanagari-Bold
I tried so many examples for above error but i am not able to fix the issue. this error i am getting on contentStream.showText(Html.fromHtml(front_page_desc).toString()); line. can someone please help me on above.
As per this link U+000A is the Unicode for new line. Any font will fail if you try to render it.
In order to avoid such error you can try something like this:
String[] lines = text.split("\\n");
for (String line : lines) {
if (!line.isBlank()) {
contentStream.showText(line);
// add new line here if you want to
}
}
My application parses html and put the content in pdf, now it needs to support multiple fonts ex: Myanmar and Chinese.
I am able to do this with phrases but not with html even for single font family
Working Code
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("/home/a2.pdf"));
Font font = FontFactory.getFont("KozMinPro-Regular", "UniJIS-UCS2-H", false);
Font font1 = FontFactory.getFont("/home/mm3.ttf", BaseFont.IDENTITY_H, false);
FontSelector fs = new FontSelector();
fs.addFont(font);
fs.addFont(font1);
Phrase phrase = fs.process("長");
phrase.add(fs.process("၀န္ထမ္းလစလႊာ( လ )"));
phrase.add(fs.process("123aab"));
document.open();
document.add(phrase);
document.close();
Tried with XMLWorker but it didn't work:
final MyFontFactory fontFactory = new MyFontFactory();
FontFactory.register("/home/Downloads/mm3.ttf");
FontFactory.setFontImp(fontFactory);
final HtmlPipelineContext htmlContext = new HtmlPipelineContext(new CssAppliersImpl(fontFactory));
final CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/a2.pdf"));
document.open();
String str="<span style=\"font-family: "Open Sans", sans-serif; white-space: pre-wrap; background-color: rgb(255, 255, 255);\">Deduc၀န္ထမ္းလစာေပးေခ်လႊာ( လစာငွေ )tions哈罗</span> ";
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
worker.parseXHtml(writer, document, is, Charset.forName("UTF-8"));
// step 5
document.close();
I want to use iText 7 (7.0.7 actually) to create a PDF/A-3 file with form fields.
I checked the examples and the jump tutorial to do so.
After adding a form field to here
like shown here, I get the following error:
Exception in thread "main" com.itextpdf.pdfa.PdfAConformanceException: An annotation dictionary shall contain the f key
at com.itextpdf.pdfa.checker.PdfA2Checker.checkAnnotation(PdfA2Checker.java:336)
at com.itextpdf.pdfa.checker.PdfAChecker.checkAnnotations(PdfAChecker.java:467)
at com.itextpdf.pdfa.checker.PdfAChecker.checkPage(PdfAChecker.java:446)
at com.itextpdf.pdfa.checker.PdfAChecker.checkPages(PdfAChecker.java:434)
at com.itextpdf.pdfa.checker.PdfAChecker.checkDocument(PdfAChecker.java:182)
at com.itextpdf.pdfa.PdfADocument.checkIsoConformance(PdfADocument.java:296)
at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:742)
at com.itextpdf.layout.Document.close(Document.java:120)
at pdfatest.C07E03_UnitedStates_PDFA_3a.createPdf(C07E03_UnitedStates_PDFA_3a.java:158)
at pdfatest.C07E03_UnitedStates_PDFA_3a.main(C07E03_UnitedStates_PDFA_3a.java:40)
This is the modified example code:
public void createPdf(String dest) throws IOException {
PdfADocument pdf = new PdfADocument(new PdfWriter(dest),
PdfAConformanceLevel.PDF_A_3A,
new PdfOutputIntent("Custom", "", "http://www.color.org",
"sRGB IEC61966-2.1", new FileInputStream(INTENT)));
Document document = new Document(pdf, PageSize.A4.rotate());
document.setMargins(20, 20, 20, 20);
//Setting some required parameters
pdf.setTagged();
pdf.getCatalog().setLang(new PdfString("en-US"));
pdf.getCatalog().setViewerPreferences(
new PdfViewerPreferences().setDisplayDocTitle(true));
PdfDocumentInfo info = pdf.getDocumentInfo();
info.setTitle("iText7 PDF/A-3 example");
//Add attachment
PdfDictionary parameters = new PdfDictionary();
parameters.put(PdfName.ModDate, new PdfDate().getPdfObject());
PdfFileSpec fileSpec = PdfFileSpec.createEmbeddedFileSpec(
pdf, Files.readAllBytes(Paths.get(DATA)), "united_states.csv",
"united_states.csv", new PdfName("text/csv"), parameters,
PdfName.Data, false);
fileSpec.put(new PdfName("AFRelationship"), new PdfName("Data"));
pdf.addFileAttachment("united_states.csv", fileSpec);
PdfArray array = new PdfArray();
array.add(fileSpec.getPdfObject().getIndirectReference());
pdf.getCatalog().put(new PdfName("AF"), array);
//Embed fonts
PdfFont font = PdfFontFactory.createFont(FONT, true);
PdfFont bold = PdfFontFactory.createFont(BOLD_FONT, true);
// Create content
Table table = new Table(new float[]{4, 1, 3, 4, 3, 3, 3, 3, 1});
table.setWidthPercent(100);
BufferedReader br = new BufferedReader(new FileReader(DATA));
String line = br.readLine();
process(table, line, bold, true);
while ((line = br.readLine()) != null) {
process(table, line, font, false);
}
br.close();
document.add(table);
// START additional code to add a form field
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
PdfFormField textFormField = PdfFormField.createText(
pdf,
new Rectangle(50, 50, 200, 15),
"vo-1-text", "bla", font, 12.0f);
form.addField(textFormField);
// END additional code to add a form field
//Close document
document.close();
}
Am I missing something?
If you can switch to iText 7.1.x, then it's relatively easy: there is a new overload for createText which allows you to set aPdfAConformanceLevel parameter, so
PdfFormField textFormField = PdfFormField.createText(
pdf,
new Rectangle(50, 50, 200, 15),
"vo-1-text", "bla", font, 12.0f,
false, // multiline parameter
PdfAConformanceLevel.PDF_A_3A // <-- this is the important one
);
If you can't, or won't, switch to iText 7.1, then you can try manually triggering the code that will set the flag:
for (PdfWidgetAnnotation wid : textFormField.getWidgets()) {
wid.setFlag(PdfAnnotation.PRINT);
}
I'm not sure if this last approach will work, because you may need to have explicitly defined the PdfWidgetAnnotation, but it is much easier to go to iText 7.1.
I am using the Hindi language for displaying header content of table in pdf but it displaying empty cell in header part of table.
I have created like as follows:
HttpServletResponse response = ServletActionContext.getResponse();
Document document = new Document();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, buffer);
writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
document.open();
PdfPTable lineItemTable = new PdfPTable(cellval);
lineItemTable.setHeaderRows(1);
PdfPCell num1 = new PdfPCell(new Phrase("No",Bold_NORMAL));
num1.setHorizontalAlignment(Element.ALIGN_CENTER);
num1.setBackgroundColor(BaseColor.LIGHT_GRAY);
lineItemTable.addCell(num1);
PdfPCell lineval = new PdfPCell(new Phrase(""));
lineval = new PdfPCell(new Phrase(HindiItenName,Bold_NORMAL));
lineval.setHorizontalAlignment(Element.ALIGN_CENTER);
lineval.setBackgroundColor(BaseColor.LIGHT_GRAY);
lineItemTable.addCell(lineval);
document.add(lineItemTable);
document.close();
response.setContentType("application/pdf;charset=ISO-8859-1");
response.setHeader("Content-Disposition","attachment;filename=Invoice-"+invNumber+".pdf");
response.getOutputStream().write(buffer.toByteArray());
This is my sample code. Can you please help to me. Thanks in advance.
Call
writer.close();
document.close();
response.setContentType("application/pdf");
Closing the writer rounds of some structures in the document. But I have seen many examples where this is not done. So I am not sure.
The content type is for binary and does not need an encoding.
On the error: pick a Unicode font, IDENTITY_H:
final String FONT = "c:/windows/... .ttf";
BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
document.add(new Paragraph("Font: " + bf.getPostscriptFontName()
+ " with encoding: " + bf.getEncoding()));
Here an embedded font, so there will no problem at the recipient's side.
This is from itextpdf.com, a book excerpt.
For a better browser experience:
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);