font registration for flying saucer with ITextRenderer - itext

I am using Flying Saucer to generate pdf from html using iText-2.1.7.
For each document I print, I do:
ITextRenderer renderer = new ITextRenderer();
for each font I use:
renderer.getFontResolver().addFont(font.getPath(),font.getName(), BaseFont.CP1252, BaseFont.EMBEDDED, null);
and then the rest of the code to create the pdf:
renderer.getSharedContext().setReplacedElementFactory(...)
renderer.getSharedContext().setUserAgentCallback(...);
renderer.setDocument(xhtmlDom,null);
renderer.layout();
renderer.createPDF(byteArrayOutputStream);
So, for each document, I register all the fonts again and again...
Is this strictly necessary? Is there any font cache service I can use, or something similar?
Thank you very much!

Related

Setting AcroField text color in itextSharp

I am using iTextSharp 5.5.3 i have a PDF with named fields i created with Adobe lifecycle I am able to fill the fields using iTextSharp but when i change the textcolor for a field it does not change. i really dont know why this is so. here is my code below
form.SetField("name", "Michael Okpara");
form.SetField("session", "2014/2015");
form.SetField("term", "1st Term");
form.SetFieldProperty("name", "textcolor", BaseColor.RED, null);
form.RegenerateField("name");
If your form is created using Adobe LifeCycle, then there are two options:
You have a pure XFA form. XFA stands for the XML Forms Architecture and your PDF is nothing more than a container of an XML stream. There is hardly any PDF syntax in the document and there are no AcroForm fields. I don't think this is the case, because you are still able to fill out the fields (which wouldn't work if you had a pure XFA form).
You have a hybrid form. In this case, the form is described twice inside the PDF file: once using an XML stream (XFA) and once using PDF syntax (AcroForm). iText will fill out the fields in both descriptions, but the XFA description gets preference when rendering the document. Changing the color of a field (or other properties) would require changing the XML and iText(Sharp) can not do that.
If I may make an educated guess, I would say that you have a hybrid form and that you are only changing the text color of the AcroForm field without changing the text color in the XFA field (which is really hard to achieve).
Please try adding this line:
form.RemoveXfa();
This will remove the XFA stream, resulting in a form that only keeps the AcroForm description.
I have written a small example named RemoveXFA using the form you shared to demonstrate this. This is the C#/iTextSharp version of that example:
public void ManipulatePdf(String src, String dest)
{
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
AcroFields form = stamper.AcroFields;
form.RemoveXfa();
IDictionary<String, AcroFields.Item> fields = form.Fields;
foreach (String name in fields.Keys)
{
if (name.IndexOf("Total") > 0)
form.SetFieldProperty(name, "textcolor", BaseColor.RED, null);
form.SetField(name, "X");
}
stamper.Close();
reader.Close();
}
In this example, I remove the XFA stream and I look over all the remaining AcroFields. I change the textcolor of all the fields with the word "Total" in their name, and I fill out every field with an "X".
The result looks like this: reportcard.pdf
All the fields show the letter "X", but the fields in the TOTAL column are written in red.
I finally found a way, guess the problem was coming from using Adobe LC, so i switched to Open Office it all worked but when i flatten the form everything disappears. I found a solution to that here ITextSharp PDFTemplate FormFlattening removes filled data
Thanks Mr Lowagie for your help

iTextSharp embedded cyrillic font in Adobe Reader

My PDF is not displayed properly with Adobe Reader. It is fine with other PDF readers so this must be a syntax issue, as I've heard that Adobe Reader is more strict with PDF syntax. The fonts seem to be twice as big as they should be but the horizontal spacing is correct, this makes the fonts overlap with each other.
This is my C# code (font creation code is at the end of this post).
Font officialUseFont = EmbeddedResources.CreateDesignFont(webform);
PdfContentByte officialUseCanvas = _stamper.GetOverContent(3);
ColumnText.ShowTextAligned(officialUseCanvas, Element.ALIGN_CENTER, new Phrase(webform.Text, officialUseFont), posX, posY, 0);
I'm using iTextSharp 5.4.2.0 with runtime v2.0.50727.
I must have embedded some fonts because the Cyrillic alphabet and Chinese alphabets were not working before but they work now. The form fields which exist in the PDF are populated with Cyrillic characters without any problems, it's only the canvas which causes the issue.
public Font CreateDesignFont(IForm webform)
{
var baseFont = GetBaseFont(fontNamespace.Length, selectedFontName);
return new Font(baseFont, webform.FontSize);
}
private static BaseFont GetBaseFont(int fontNamespaceLength, string selectedFontName)
{
byte[] fontBuffer;
using (var stream = (Assembly.GetExecutingAssembly().GetManifestResourceStream(selectedFontName)))
{
fontBuffer = new byte[stream.Length];
stream.Read(fontBuffer, 0, fontBuffer.Length);
}
var fontfile = selectedFontName.Substring(fontNamespaceLength);
var customFont = BaseFont.CreateFont(fontfile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, BaseFont.CACHED, fontBuffer, null);
return customFont;
}
The code snippet you're providing isn't sufficient. The problem originates in whatever happens when you do EmbeddedResources.CreateDesignFont(webform);
If the font isn't shown in Adobe Reader, you didn't embed the font. Maybe you think you do, but judging by the behavior of the PDF viewers, you didn't.
Can you provide a screen shot of the Document Properties, more specifically the "Fonts" tab?
UPDATE
I tried writing my own code snippet, and I wasn't able to reproduce the problem. So I took another look at your code, and I saw that you're caching the font, but you've already used ArialMT using the WINANSI encoding to fill out the fields on page 1. IMO (I don't have the time to check) that's incompatible with using the same font from cache using IDENTITY_H. If you don't cache the font (why would you? you're passing the fontBuffer! no need to store the font in a cache if you're already caching the font bytes yourself), your problem will probably be solved.
The problem stemmed from the fact I was using .otf fonts. When I changed to .ttf the problem disappeared.

Rich Text Content Fields with iTextSharp

I'm using iTextSharp to create pdf files on the fly for my users to save on their computers. Currently the way it works is that I had several pdf templates that iTextSharp opens, sets fields from the database and save on user computer.
I'm having real problems with adding rich content into the body field which the users enter using a Rich Text editor (NiceEdit). It contains really simple options such as bullets, bold, italic, font colors, sizes etc. which is all what they need. I tried all possible options out there but nothing seem to help.
PdfReader reader = new PdfReader(originalReport.ToString());
PdfStamper stamper = new PdfStamper(reader, new FileStream(report, FileMode.Create));
AcroFields fields = stamper.AcroFields;
fields.SetFieldProperty("body", "setfflags", PdfFormField.FF_RICHTEXT, null);
fields.SetFieldRichValue("body", bodyValue.ToString());
fields.GenerateAppearances = false;
I tried flattening the form but it doesn't display the field at all. If I didn't flatten the form then the field displays the content but with no format at all (even new lines are removed) and if I used the SetField option instead of the SetFieldRichValue I get a string of the html content
I also tried allowing the pdf template field to "Allow Rich Text" from acrobat pro but this gives an exception and halts the pdf :)
Also please note that since I'm using a template that depends on the type of the user, the SetField option is used, I don't create the document from scratch hence I don't use paragraphs which I can get if I used the HTMLWorker and simply add to a document
Any help please?

iText, What's going on with Font, BaseFont and createFont()?

There is a lot of mystery to me about what is going on with font and basefont. Especially when it comes to the constructor. The iText website gives this line as example code for new fonts
BaseFont unicode = BaseFont.createFont("c:/windows/fonts/arialuni.ttf",
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);
I can get this call to work:
BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1257,
BaseFont.EMBEDDED);
But if I replace BaseFont.CP1257 with say BaseFont.HELVETICA then it doesn't work and I get a page that says "failed to load pdf document."
I tried looking through the class file and I can't seem to figure out what that second parameter is (I'm assuming it is something like a backup font in case the first font doesn't work, like in HTML) and I can't figure out why some fonts would work and not others.
To load it from inside your jar use the leading slash otherwise, just use the absolute path of your font ("C:[...]\fonts\Sansation_Regular.ttf"). For example:
Font font = FontFactory.getFont("/fonts/Sansation_Regular.ttf",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0.8f, Font.NORMAL, BaseColor.BLACK);
BaseFont baseFont = font.getBaseFont();
The relative path of the font is: 'src/main/resources/fonts'
Using Itext 5.4.5
example: https://code.google.com/p/jhocr/source/browse/trunk/src/main/java/com/googlecode/jhocr/converter/HocrPageProcessor.java
The second parameter is the encoding.
Refer to documentation here for more information.
This is what worked for me. Old post, but I couldn't find a simple answer.
//Here you setup the font that you want. I put it under the root/Content/fonts folder in my project
Font font = FontFactory.GetFont("~/Content/fonts/ARIALN.ttf", BaseFont.CP1252,false, 9);
//Here I create the paragraph then assign the font to it at the end
var addressAttn = new Paragraph("Attn: Manager, Billing Services", font);

Pipeline chart control

I'm looking for a chart control that is able to display data like this:
But it must not be Silverlight, Flash or other technology forcing user to install plugin.
It would be best it the control could use HTML5, JavaScript, C#
For me it looks like a simple table with data. You can always later on dynamically render the images on the column 1 and 2 with C# using System.Drawing. Using a charting control for drawing 2 simple images sounds like an overkill while with C# you can easily do what you need and present it to client using the web standards with no plugins.
To overlay 2 images and write some text on it:
string graphPath = Server.MapPath("graph.png");
string iconPath = Server.MapPath("icon.png");
// Prepare the template image
System.Drawing.Image template = Bitmap.FromFile(graphPath);
Graphics gfx = Graphics.FromImage(template);
// Draw an icon on it on x=70, y=70
Bitmap icon = new Bitmap(iconPath);
gfx.DrawImage(icon, new Point(70, 70));
// Draw a string on it on x=150, y=150
Font font = new Font("Arial", 12.0f);
gfx.DrawString("11/14/2009", font, Brushes.Black, new Point(150, 150));
// Output the resulting image
Response.ContentType = "image/png";
template.Save(Response.OutputStream, ImageFormat.Png);
See, you end up coding very little and you don't surrender yourself playing by the rules dictated by a charting control.