First off I'm not that great with C# and it's been a while since I've worked with it..
I'm making a windows form for a friend that delivers packages. So I want to transfer his current paper form, into a .pdf with the library iTextSharp. He still needs to print the form to get the customer signature and so on.
What I need:
I want the table to have a little headline, "Company name" for example, the text should be a little smaller than the text input from the windows form(richTextBox1)
Currently I'm using cells and was wondering if I can use 2 different font sizes within the same cell?
What I have:
table.AddCell("Static headline" + Chunk.NEWLINE + richTextBox1.Text);
What I "want":
var normalFont = FontFactory.GetFont(FontFactory.HELVETICA, 9);
var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12);
table.AddCell("Static headline", boldFont + Chunk.NEWLINE + richTextBox1.Text, normalFont);
You're passing a String and a Font to the AddCell() method. That's not going to work. You need the AddCell() method that takes a Phrase object or a PdfPCell object as parameter.
A Phrase is an object that consists of different Chunks, and the different Chunks can have different font sizes. Please read chapter 2 of my book for more info about this object.
Phrase phrase = new Phrase();
phrase.Add(
new Chunk("Some BOLD text", new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD))
);
phrase.Add(new Chunk(", some normal text", new Font()));
table.AddCell(phrase);
A PdfPCell is an object to which you can add different objects, such as Phrases, Paragraphs, Images,...
PdfPCell cell = new PdfPCell();
cell.AddElement(new Paragraph("Hello"));
cell.AddElement(list);
cell.AddElement(image);
In this snippet list is of type List and image is of type Image.
The first snippet uses text mode; the second snippet uses composite mode. Cells behave very differently depending on the mode you use.
This is all explained in the documentation; you can find hundreds of C# examples here.
Related
I'm trying to automate a table cell format with VSTO. The output I'm looking for is:
Particularly note the difference in font size between the LineItem and LineItemDescirption tokens.
How can write these two different formats to the same cell within C#?
I currently have the following:
var r = table.Cell(row, 1).Range;
r.Text = item.Name + Environment.NewLine + item.Description;
r.Font.Size = 11;
But I can't find out how to do this as two separate entities. I thought Range.Sentences would help (to return different ranges I could then apply the style individually to) but the compiler complains it doesn't exist.
I can't seem to write two ranges to the same cell. I can only seem to capture the full text of any given range...
I'm (obviously) not fluent in the Word object model. If someone can give me a push in the right direction that'd be great. Thanks
Document doc = new Document(iTextSharp.text.PageSize.LETTER.Rotate(), 10, 10, 5, 5);
string nazivPDFa = txt_datumFiskalnogIsecka.Text +" "+ txt_nazivKompanije.Text;
PdfWriter pdf = PdfWriter.GetInstance(doc, new FileStream(nazivPDFa + ".pdf", FileMode.CreateNew));
doc.Open();
Paragraph klijent = new Paragraph(ispisiKlijenta.Text);
PdfPTable tabelaNK = new PdfPTable(1);
PdfPCell kl = new PdfPCell(new Phrase(klijent));
kl.BorderColor = BaseColor.BLACK;
tabelaNK.AddCell(kl);
doc.Add(tabelaNK);
I have create PDF document with itextSharp and when I fill PDF with some text who is in Serbian, he doesnt show me chars like š,ć,č,đ,ž.
Example: I wrote "nešto" and I get "neto".
I have a lot of thinks at that PDF and it will take forever to give to all elements current culture.
You aren't using a font when you create your Paragraph. In that case, the Standard Type 1 font Helvetica will be used and it won't be embedded. As Helvetica only supports a limited set of characters, your glyphs won't appear. This is very well documented in the official documentation. It's a pity you try to run before you've learned how to walk.
Several things can be at play.
First, you need to make sure that the encoding of ispisiKlijenta.Text is correct. For instance, is that string in CP1250 or in Unicode? When you write KlijenT.Add("Tekući račun: " +txt_brRacunaKompanije.Text);, you are writing bad code (at least if you were writing Java) because you introduce special characters in your code that may disappear when the code is compiled or executed using a different environment using a different encoding.
Then, you need to provide a font program that knows how to draw the glyphs you need. For instance: Helvetica doesn't know about CP1250, but arial.ttf does (and so do many other fonts, but you need to check first).
Then, you need to decide how you'll use that font. Will you use embed the font as a simple font, as is done in the EncodingExample where we create this PDF, or will you embed the font as a composite font, as is done in the UnicodeExample where we create this PDF. Both PDFs may look identical to you, but they aren't. The choice you make will have an impact on the design of your application.
Once you've made a decision about the font and once you've create a Font object, e.g. named font, you need to use that object when creating a Paragraph.
I am working on a Windows Application implemented in C#. One of the requirements is for the user to be able to select a set of fonts and save them into a database. Among the information that I need to store for the font are:
The name of the font
Size
Whether its bold, italic, underline
So far I have this information stored as separate fields in the database. Latter I build the Font object from this information. However, i find it impossible to create a new object with all the needed settings (e.g., a font that is both bold and italic).
To illustrate I do something like this (note that I work with EF, so the methods are just for illustration):
string font_name = GetFontNameFromDatabase();
string font_size = GetFontSizeFromDatabase();
...
Font f = new Font(font_name, font_size);
My question is whether there is a convenient way to store the font object in SLQ Server Database. Maybe as a binary field?
You can use the FontConverter class to serialize and deserialize your fonts:
var fc = new FontConverter();
Font f1 = new Font("Times New Roman", 12);
var fontAsString = fc.ConvertToInvariantString(f1); // "Times New Roman, 12pt"
Font f2 = (Font)fc.ConvertFromInvariantString(fontAsString);
Console.WriteLine(f2.ToString()); // [Font: Name=Times New Roman, Size=12, ...]
I'm trying to use the watermark plugin to write text on images for my project. Right now I'm trying to find out how to set a "width" for a writing box so I can get automatic line returns. Is there a way to do this with the watermark plugin?
Also I'm trying to see if I can get a "text-align: center" effect when I'm writing my text (possibliy in relation to that set width), how could I get that setup?
I'm thinking that the alternative to this would be to have code driven line returns and centering, but this would mean that I would have to count the width of my characters and this seems like a world of pain hehe
Here is a code sample that shows what I'm doing (this currently works):
var c = Config.Current;
var wp = c.Plugins.Get<WatermarkPlugin>();
var t = new TextLayer();
t.Text = panty.Message;
t.TextColor = (System.Drawing.Color) color;
t.Font = fonts[myFunObject.Font];
t.FontSize = fontSize[myFunObject.LogoPosition];
t.Left = new DistanceUnit(5, DistanceUnit.Units.Pixels);
t.Top = new DistanceUnit(5, DistanceUnit.Units.Pixels);
wp.NamedWatermarks["myFunObjectMessage"] = new Layer[] { t };
EDIT: I also have to mention that the text I'm writing is user submitted so it's different everytime. If you want a similar case, think about thos funny cat images with funny text captions on them. This project is quite similar to that. (Minus the cats)
Thanks for the help!
Basically, System.Drawing (and therefore the current version of Watermark) are very primitive about line wrapping.
As you mentioned, you can do hacky stuff with character counting and separate MeasureString calls with loops, but the results are only barely acceptable.
You may try to fork the Watermark source code and hack support for your use case. I don't see a way to improve Watermark in a generic way without replacing the underlying graphics engine first (which may happen anyway).
System.Drawing has unsurpassed image resampling quality. Text wrapping, though, it kind of stinks at.
I have a bunch of PDF files- I read these as requested into a byte array and then also pass it to a iTextSharp PdfReader instance. I want to then grab the dimensions of each page- in pixels. From what I've read so far it seems by PDF files work in points- a point being a configurable unit stored in some kind of dictionary in an element called UserUnit.
Loading my PDF File into a PdfReader, what do I need to do to get the UserUnit for each page (apparently it can vary from page to page) so I can then get the page dimensions in pixels.
At present I have this code, which grabs the dimensions for each page in "points" - guess I just need the UerUnit, and can then multiply these dimensions by that to get pixels or something similar.
//Create an object to read the PDF
PdfReader reader = new iTextSharp.text.pdf.PdfReader(file_content);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
Rectangle dim = reader.GetPageSize(i);
int[] xy = new int[] { (int)dim.Width, (int)dim.Height }; // returns page size in "points"
page_data[objectid + '-' + i] = xy;
}
Cheers!
Allow me to quote from my book:
iText in Action - Second Edition, page 9:
FAQ What is the measurement unit in PDF documents? Most of the measurements
in PDFs are expressed in user space units. ISO-32000-1 (section 8.3.2.3) tells us
“the default for the size of the unit in default user space (1/72 inch) is
approximately the same as a point (pt), a unit widely used in the printing
industry. It is not exactly the same; there is no universal definition of a point.”
In short, 1 in. = 25.4 mm = 72 user units (which roughly corresponds to 72 pt).
On the next page, I explain that it’s possible to change the default value of the user unit, and I add an example on how to create a document with pages that have a different user unit.
Now for your question: suppose you have an existing PDF, how do you find which user unit was used? Before we answer this, we need to take a look at ISO-32000-1.
In section 7.7.3.3Page Objects, you'll find the description of UserUnit in Table 30, "Entries in a page object":
(Optional; PDF 1.6) A positive number that shall give the size of
default user space units, in multiples of 1⁄72 inch. The range of
supported values shall be implementation-dependent. Default value: 1.0
(user space unit is 1⁄72 inch).
This key was introduced in PDF 1.6; you won't find it in older files. It's optional, so you won't always find it in every page dictionary. In my book, I also explain that the maximum value of the UserUnit key is 75,000.
Now how to retrieve this value with iTextSharp?
You already have Rectangle dim = reader.GetPageSize(i); which returns the MediaBox. This may not be the size of the visual part of the page. If there's a CropBox defined for the page, viewers will show a much smaller size than what you have in xy (but you probably knew that already).
What you need now is the page dictionary, so that you can retrieve the value of the UserUnit key:
PdfDictionary pageDict = reader.GetPageN(i);
PdfNumber userUnit = pageDict.GetAsNumber(PdfName.USERUNIT);
Most of the times userUnit will be null, but if it isn't you can use userUnit.FloatValue.