itextSharp - htmlString to pdf Unicode are missing - itext

When I am trying to generate PDF from HTML, some Turkish characters like ĞÜŞİÖÇ ğüşıöç are missing in PDF, I see a space in place of these characters but i want to print that character.
My code is:
public virtual void print pdf(string html, int id)
{
String htmlText = html.ToString();
Document document = new Document();
string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");
PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+id+".pdf",
FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw =
new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(htmlText));
document.Close();
}
please reply i need suggestion
...
regards

I have finally find a solution for this problem, by this you can print all Turkish characters.
String htmlText = html.ToString();
Document document = new Document();
string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");
PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+Name+".pdf", FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
FontFactory.Register(Path.Combine(_webHelper.MapPath("~/App_Data/Pdf/arial.ttf")), "Garamond"); // just give a path of arial.ttf
StyleSheet css = new StyleSheet();
css.LoadTagStyle("body", "face", "Garamond");
css.LoadTagStyle("body", "encoding", "Identity-H");
css.LoadTagStyle("body", "size", "12pt");
hw.SetStyleSheet(css);
hw.Parse(new StringReader(htmlText));

Related

About IText AcroFields

I am trying to generate pdf from template using iText. I've set value in AcroFields. when I opening output file, there is nothing on it.Is there anyone who had same problem before? .
FileOutputStream fos = new FileOutputStream(destPath);
PdfReader reader = new PdfReader(templatePath);
PdfStamper stamp = new PdfStamper(reader, fos);
AcroFields form = stamp.getAcroFields();
form.setField("parttype", "1dafd");
stamp.setFormFlattening(true);
stamp.close();
fos.flush();
fos.close();

how to change code so it works with itext 7

The following code works nicely with iText 5:
LEVEL = PdfAConformanceLevel.PDF_A_3A
writer = PdfAWriter.getInstance(document, baos, LEVEL)
What is the correct syntax for iText 7?
Where can I find examples and documentation about iText 7?
why so negative? Seems like you want to put extra pressure on me to write documentation. That's kind of frustrating. I think that encouragement works better. Nevertheless, your claim that there's no documentation is wrong.
See Chapter 7: Creating PDF/UA and PDF/A documents of the iText 7: Jump-Start Tutorial
You overlooked the UnitedStates_PDFA_3a example in which we have a CSV file that we convert to a PDF/A-3 document adding that CSV file as attachment.
public void createPdf(String dest) throws IOException, XMPException {
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);
//Close document
document.close();
}
public void process(Table table, String line, PdfFont font, boolean isHeader) {
StringTokenizer tokenizer = new StringTokenizer(line, ";");
while (tokenizer.hasMoreTokens()) {
if (isHeader) {
table.addHeaderCell(new Cell().setHorizontalAlignment(HorizontalAlignment.CENTER).add(new Paragraph(tokenizer.nextToken()).setHorizontalAlignment(HorizontalAlignment.CENTER).setFont(font)));
} else {
table.addCell(new Cell().setHorizontalAlignment(HorizontalAlignment.CENTER).add(new Paragraph(tokenizer.nextToken()).setHorizontalAlignment(HorizontalAlignment.CENTER).setFont(font)));
}
}
}

How to fill XFA from using iText so it is Foxit Reader comptible

I used examples available on web to create an application that is able to get xml structure of XFA form and then set it back filled. Important code looks like this:
public void readData(String src, String dest)
throws IOException, ParserConfigurationException, SAXException,
TransformerFactoryConfigurationError, TransformerException {
FileOutputStream os = new FileOutputStream(dest);
PdfReader reader = new PdfReader(src);
XfaForm xfa = new XfaForm(reader);
Node node = xfa.getDatasetsNode();
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
if ("data".equals(list.item(i).getLocalName())) {
node = list.item(i);
break;
}
}
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(node), new StreamResult(os));
reader.close();
}
public void fillPdfWithXmlData(String src, String xml, String dest)
throws IOException, DocumentException {
PdfReader.unethicalreading = true;
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest), '\0', true);
AcroFields form = stamper.getAcroFields();
XfaForm xfa = form.getXfa();
xfa.fillXfaForm(new FileInputStream(xml));
stamper.close();
reader.close();
}
When I use it to fill this form: http://www.vzp.cz/uploads/document/tiskopisy-pro-zamestnavatele-hromadne-oznameni-zamestnavatele-verze-2-pdf-56-kb.pdf it works fine and I can see the filled form in Acrobat Reader. However, if I open the document in Foxit Reader I see a blank form (tested in latest version and 5.x version).
I tried to play a little bit with it and got these XfaForm(...).getDomDocument() data:
Filled by Acrobat Reader: http://pastebin.com/kXKyh9EM
Filled by Foxit Reader: http://pastebin.com/tiZ7EmfE
Filled by iText: http://pastebin.com/tTKLMERC
Filled by Foxit Reader after a fill by iText: http://pastebin.com/Uuq0jS4b
The field which was filled is . Is it possible to use iText in a way that it works even with Foxit Reader (and the XFA signature stays?)
In your Filled by iText example there's a superfluous <xfa:data> element:
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
<xfa:data>
<HOZ>
<!-- rest of your data here -->
</HOZ>
</xfa:data>
</xfa:data>
<!-- data description -->
</xfa:datasets>
This is because the fillXfaForm() method of XfaForm expects the XML data without <xfa:data> as the root element. So your XML data should just look like:
<HOZ>
<!-- rest of your data here -->
</HOZ>
I see that your readData() method that extract the existing form data including the <xfa:data> element:
<xfa:data>
<HOZ>
<!-- rest of your data here -->
</HOZ>
</xfa:data>
Stripping the outer element should fix your problem. For example:
XfaForm xfa = new XfaForm(reader);
Node node = xfa.getDatasetsNode();
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
if ("data".equals(list.item(i).getLocalName())) {
node = list.item(i);
break;
}
}
// strip <xfa:data>
node = node.getFirstChild();
// Transformer code here

iText for .NET barcode

I try to create a PDF with a EAN13 Bar-code using the iTextSharp library.
I try to generate a barcode with the value "023942432852".
iTextSharp.text.Image imageEAN = codeEan.CreateImageWithBarcode(cb, null, null);
throws System.IndexOutOfRangeException.
There is the code:
Document pdfdoc = new Document(pageSize, _margSx, _margDx, _margUp, _margBo);
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(_path + #"\Barcode.pdf", FileMode.Create));
pdfdoc.Open();
PdfContentByte cb = writer.DirectContent;
pdfdoc.PageSize.BackgroundColor = BaseColor.GRAY;
BarcodeEAN codeEan = new BarcodeEAN();
if (CreaChecksum)
codeEan.GenerateChecksum = true;
codeEan.ChecksumText = true;
codeEan.CodeType = Barcode.EAN13;
codeEan.Code = barcode;
iTextSharp.text.Image imageEAN = codeEan.CreateImageWithBarcode(cb, null, null);
imageEAN.ScaleAbsolute(100, 40);
imageEAN.SetAbsolutePosition(pdfdoc.PageSize.Right - 150f, pdfdoc.PageSize.Bottom + 30f);
pdfdoc.Add(imageEAN);
As the name indicates an EAN13 bar code requires 13 digits, just like an EAN8 bar code requires 8 digits. You are trying to create a bar code for this string:
"023942432852"
When I count the number of digits in this string, I only find 12. One digit is missing. Please complete the string so that its length is 13.

Creating a PDF back page using Itext

I am currently using iText (Java) to create a PDF document.
This PDf document is meant to be a Businesscard to be printed.
This is part of my code:
public void write() throws DocumentException, FileNotFoundException, IOException {
String extension = ".pdf";
String file = "testerPDF";
String filename = file + extension;
Document doku = new Document(PageSize.A4, 10,20,50,150);
PdfWriter writer = PdfWriter.getInstance(doku, new FileOutputStream(new File(filename)));
doku.open();
Phrase textblock = new Phrase();
// jetzt durch den Vector iterarieren
for(int i = 0; i < vector.size(); i++) {
Chunk chunk=new Chunk((String)vector.get(i));
textblock.add(chunk);
}
doku.add(new Paragraph(textblock));
doku.close();
writer.close();
}
So I need now a way to also write a Back Page for this created PDF. In such a way that the document would look like a Business card on Paper.