itextsharp how to add line height to the chunk content - c#

I am using the following code in .net using iTextSharp
PdfPTable Header2 = new PdfPTable(2);
Header2.DefaultCell.Padding = 4;
Header2.WidthPercentage = 90;
Phrase pp4 = new Phrase();
pp4.Add(new Chunk(" Text of the first line\n", FontFactory.GetFont("Arial", 17, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
pp4.Add(new Chunk(" Text of the second line", FontFactory.GetFont("Arial", 15, iTextSharp.text.Font.ITALIC, iTextSharp.text.Color.BLACK)));
PdfPCell hcell3 = new PdfPCell(new Phrase(pp4));
hcell3.HorizontalAlignment = Element.ALIGN_LEFT;
hcell3.VerticalAlignment = Element.ALIGN_TOP;
hcell3.BorderColor = iTextSharp.text.Color.BLACK;
hcell3.BackgroundColor = new iTextSharp.text.Color(255, 255, 255);
Header2.AddCell(hcell3);
The output shows text very close to each other in various lines. I need to put up some vertical space between two lines.
How can I achieve this in the code above?

The space between the lines is called the leading, referring to the small strips of lead that were put between different lines of type in the early days of printing.
You have two options.
If you are using PdfPCell in text mode (in case you didn't know: you do), you can change the leading like this:
PdfPCell hcell3 = new PdfPCell(new Phrase(pp4));
hcell3.Leading = 20;
If you are using PdfPCell in composite mode, you can change the leading like this:
pp4.Leading = 20;
PdfPCell hcell3 = new PdfPCell();
hcell3.AddElement(pp4);
In the former case, you work with a single Phrase in the cell, and all the content of that cell takes a single value for the leading. In the latter case, the leading of the cell is ignored. Instead the leading of the objects you are adding to the cell (using the AddElement() method) is used. In the latter case, it's possible to use more than one leading in the same cell.
Please not that you're using an old version of iText. We don't call it iTextSharp anymore, we call it iText for .NET. The most recent version is 7.1. If you're just starting, please upgrade as old versions of iText are no longer supported for users who aren't a customer. See the iText for .NET download page.

Related

Write text to fixed position in paragraph with iText7

I try to write a pdf file with a header, logo and table using iText7 in c#.
I never used iText7 before and therefore I don't know how to write text in a paragraph to a fixed position.
Right now I am just using tabstops as anchors for my text. But the problem here is, when the string is too long everything following in the line will be shifted by a tabstop and the "columns" in the header aren't aligned anymore.
The following picture is what I want too achieve:
This picture shows what happens if a string gets too long (in this example I used a long username):
Here is a code snippet I use to write one line of the header:
// generate 8 tabstops to split pdf in equal sections
List<TabStop> tabStops = new List<TabStop>();
for (uint i = 0; i < 8; i++)
{
float tabSize = pageSize.GetWidth() / 8;
tabStops.Add(new TabStop(tabSize, TabAlignment.LEFT));
}
Paragraph p = new Paragraph();
p.SetFontSize(10);
// add tabstops to paragraph for text alignment
p.AddTabStops(tabStops);
// add title of header
p.Add(title1).Add("\n");
// write line one of header
p.Add("Serie: ").Add(new Tab()).Add(info.serial.ToString())
.Add(new Tab()).Add(new Tab())
.Add("Input CSV: ").Add(new Tab()).Add(info.inputFileName)
.Add(new Tab()).Add(new Tab()).Add("Out-Series: ")
.Add(info.serial.ToString()).Add("\n");
// line 2...
p.Add("User: ").Add(new Tab()).Add(info.username)
.Add(new Tab()).Add(new Tab()).Add(new Tab())
.Add("qPCR-Datei: ").Add(new Tab()).Add(info.qpcr1FileName)
.Add(new Tab()).Add(new Tab()).Add(new Tab())
.Add("STR-Out: ").Add(strFileName).Add("\n");
I hope someone can help me show me a better way of text alignment or has information where to look at.
Another nice tip would be how I can keep linebreaks in the same tab stop section. for example if a file name gets too long (s. "STR-Out: " in picture) the linebreak will be executed but the part of the filename in the new line should stay at the tab stop behind "STR-OUT: "
Instead of Tab/Tabspace use Tables and Cells so that alignment will be proper.
Create table of column 8 size (Label, Value, space , Label, Value, Space, Label, Value)
Use this sample Code.
PdfPTable table = new PdfPTable(8);
PdfPCell cell;
cell = new PdfPCell();
cell.setRowspan(2); //only if spanning needed
table.addCell(cell);
for(int aw=0;aw<8;aw++){
table.addCell("hi");
}
Thanks #shihabudheenk for pointing me in the right direction with the idea of using a table.
Just had to adjust some code to iText7.
First thing is that
Table headerTable = new Table().SetBorder(Border.NO_BORDER);
has no effect in iText7, you have to set the option for each cell individually like:
Cell cell = new Cell().SetBorder(Border.NO_BORDER);
but here is the problem that
cell.Add()
in iText7 only accepts IBlockElement as parameter so i have too use it like this:
cell.Add(new Paragraph("text");
which is pretty annoying doing that for every cell over and over again. Therefore i used a removeBorder function as suggested here
So the final code I use to build the header looks like this:
// initialize table with fixed column sizes
Table headerTable = new Table(UnitValue.CreatePercentArray(
new[] { 1f, 1.2f, 1f, 1.8f, 0.7f, 2.5f })).SetFixedLayout();
// write headerline 1
headerTable.AddCell("Serie: ").AddCell(info.serial.ToString())
.AddCell("Input CSV: ")
.AddCell(info.inputFileName)
// write remaining lines...
....
// remove boarder from all cells
removeBorder(headerTable);
private static void removeBorder(Table table)
{
foreach (IElement iElement in table.GetChildren())
{
((Cell)iElement).SetBorder(Border.NO_BORDER);
}
}

How to change default font and color for iTextSharp table?

Is there any way, how to change default table's iTextSharp font and cell's color?
I have a table, where I can change a font, but that would have to be done on every single cell - which is very unfortunate. Most probably there is a better way, but I haven't found it.
The reason I want to do this change is, that default font does not support Czech characters.
I have following code:
PdfPTable subTable = new PdfPTable(4);
Font bigFont = FontFactory.GetFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, 8, Font.NORMAL, BaseColor.RED);
PdfPCell subCell = new PdfPCell(new Phrase("Bělení fáze 1",bigFont));
subCell.BackgroundColor = new BaseColor(196, 231, 234);
subTable.AddCell(subCell);
subTable.AddCell("Test");
First printed cell is going to have defined font - arial, as well as cell's color. Second cell will have all in default.
I also tried following command, but that did not help at all:
subTable.DefaultCell.Phrase = new Phrase() { Font = bigFont };
Thanks for any hints.
Need to split them into separate chunks that use different Font and add them to a phase and then add them to the PdfPTable as a cell.
See here:
iTextSharp - Is it possible to set a different font color for the same cell and row?
I had the same problem and came accross this old question.
While iTextSharp is deprecated and replaced by iText 7, I had to use the old iTextSharp.
For anyone in the same position, here is what I ended up with.
Like the original asker, I first tried to achieve it that way, which - in my opinion - would be intuitive:
var table = new PdfPTable(4); // <- use wrapper class here
table.DefaultCell.Phrase = new Phrase() { Font = myDefaultFont };
which obviously doesn't work. But you can make it work by writing a wrapper class for PdfPTable and overriding its AddCell(string text) like this
public class MyPdfTable : PdfPTable
{
public new void AddCell(string text)
{
Phrase defaultPhrase = DefaultCell.Phrase;
Phrase phrase = defaultPhrase == null ? new Phrase(text) : new Phrase(text, defaultPhrase.Font);
base.AddCell(phrase);
// for some reason iTextSharp sets this to null after AddCell() is called, so we restore it
DefaultCell.Phrase = defaultPhrase;
}
One could implement this as an extension method for PdfPTable as well, but I ended up with the above solution since I was working with legacy code.
That way the only thing I had to change was the type when newing the table up and not each and every call to AddCell().
Hope it helps anyone.

Alignment in Itextsharp [duplicate]

I want to display two pieces of content (it may a paragraph or text) to the left and right side on a single line. My output should be like
Name:ABC date:2015-03-02
How can I do this?
Please take a look at the LeftRight example. It offers two different solutions for your problem:
Solution 1: Use glue
By glue, I mean a special Chunk that acts like a separator that separates two (or more) other Chunk objects:
Chunk glue = new Chunk(new VerticalPositionMark());
Paragraph p = new Paragraph("Text to the left");
p.add(new Chunk(glue));
p.add("Text to the right");
document.add(p);
This way, you will have "Text to the left" on the left side and "Text to the right" on the right side.
Solution 2: use a PdfPTable
Suppose that some day, somebody asks you to put something in the middle too, then using PdfPTable is the most future-proof solution:
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100);
table.addCell(getCell("Text to the left", PdfPCell.ALIGN_LEFT));
table.addCell(getCell("Text in the middle", PdfPCell.ALIGN_CENTER));
table.addCell(getCell("Text to the right", PdfPCell.ALIGN_RIGHT));
document.add(table);
In your case, you only need something to the left and something to the right, so you need to create a table with only two columns: table = new PdfPTable(2).
In case you wander about the getCell() method, this is what it looks like:
public PdfPCell getCell(String text, int alignment) {
PdfPCell cell = new PdfPCell(new Phrase(text));
cell.setPadding(0);
cell.setHorizontalAlignment(alignment);
cell.setBorder(PdfPCell.NO_BORDER);
return cell;
}
Solution 3: Justify text
This is explained in the answer to this question: How justify text using iTextSharp?
However, this will lead to strange results as soon as there are spaces in your strings. For instance: it will work if you have "Name:ABC". It won't work if you have "Name: Bruno Lowagie" as "Bruno" and "Lowagie" will move towards the middle if you justify the line.
I did this to work and its working
Document document = new Document(PageSize.A4, 30, 30, 100, 150);
document.SetPageSize(iTextSharp.text.PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
writer.PageEvent = new ITextEvents();
document.Open();
iTextSharp.text.Font fntHead2 = new iTextSharp.text.Font(bfntHead, 11, 1, BaseColor.BLACK);
Paragraph para = new Paragraph();
Chunk glue = new Chunk(new VerticalPositionMark());
Phrase ph1 = new Phrase();
Paragraph main = new Paragraph();
ph1.Add(new Chunk("Left Side", fntHead2));
ph1.Add(glue); // Here I add special chunk to the same phrase.
ph1.Add(new Chunk("Right Side", fntHead2));
para.Add(ph1);
document.Add(para);

How to align two paragraphs to the left and right on the same line?

I want to display two pieces of content (it may a paragraph or text) to the left and right side on a single line. My output should be like
Name:ABC date:2015-03-02
How can I do this?
Please take a look at the LeftRight example. It offers two different solutions for your problem:
Solution 1: Use glue
By glue, I mean a special Chunk that acts like a separator that separates two (or more) other Chunk objects:
Chunk glue = new Chunk(new VerticalPositionMark());
Paragraph p = new Paragraph("Text to the left");
p.add(new Chunk(glue));
p.add("Text to the right");
document.add(p);
This way, you will have "Text to the left" on the left side and "Text to the right" on the right side.
Solution 2: use a PdfPTable
Suppose that some day, somebody asks you to put something in the middle too, then using PdfPTable is the most future-proof solution:
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100);
table.addCell(getCell("Text to the left", PdfPCell.ALIGN_LEFT));
table.addCell(getCell("Text in the middle", PdfPCell.ALIGN_CENTER));
table.addCell(getCell("Text to the right", PdfPCell.ALIGN_RIGHT));
document.add(table);
In your case, you only need something to the left and something to the right, so you need to create a table with only two columns: table = new PdfPTable(2).
In case you wander about the getCell() method, this is what it looks like:
public PdfPCell getCell(String text, int alignment) {
PdfPCell cell = new PdfPCell(new Phrase(text));
cell.setPadding(0);
cell.setHorizontalAlignment(alignment);
cell.setBorder(PdfPCell.NO_BORDER);
return cell;
}
Solution 3: Justify text
This is explained in the answer to this question: How justify text using iTextSharp?
However, this will lead to strange results as soon as there are spaces in your strings. For instance: it will work if you have "Name:ABC". It won't work if you have "Name: Bruno Lowagie" as "Bruno" and "Lowagie" will move towards the middle if you justify the line.
I did this to work and its working
Document document = new Document(PageSize.A4, 30, 30, 100, 150);
document.SetPageSize(iTextSharp.text.PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
writer.PageEvent = new ITextEvents();
document.Open();
iTextSharp.text.Font fntHead2 = new iTextSharp.text.Font(bfntHead, 11, 1, BaseColor.BLACK);
Paragraph para = new Paragraph();
Chunk glue = new Chunk(new VerticalPositionMark());
Phrase ph1 = new Phrase();
Paragraph main = new Paragraph();
ph1.Add(new Chunk("Left Side", fntHead2));
ph1.Add(glue); // Here I add special chunk to the same phrase.
ph1.Add(new Chunk("Right Side", fntHead2));
para.Add(ph1);
document.Add(para);

Bold a single word within a sentence with iTextSharp

Is it possible to bold a single word within a sentence with iTextSharp? I am trying to bold several individual words without having to break the string into individual phrases.
I want to this type of out put
Eg:REASON(S) FOR CANCELLATION: See Statutory reason(s) designated by Code No(s) 1 on the reverse side hereof.
My actual output is below
Eg:REASON(S) FOR CANCELLATION: See Statutory reason(s) designated by Code No(s) 1 on the reverse side hereof.
Code
pdftb4 = new PdfPTable(1);
pdftb4.WidthPercentage = 100;
width = new float[1];
width[0] = 0.7F;
pdftb4.SetWidths(width);
pdfcel4 = new PdfPCell(new Phrase("\n REASON(S) FOR CANCELLATION: See Statutoryreason(s) designated by Code No(s) 1 on the reverse side hereof", docBlackFont10));
pdfcel4.Border = 0;
pdfcel4.HorizontalAlignment = Element.ALIGN_LEFT;
pdftb4.AddCell(pdfcel4);
objDocument.Add(pdftb4);
somebody please help me
The way to accomplish what you are trying is with Chunks. A simple example is:
var normalFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12);
var phrase = new Phrase();
phrase.Add(new Chunk("REASON(S) FOR CANCELLATION:", boldFont));
phrase.Add(new Chunk(" See Statutoryreason(s) designated by Code No(s) 1 on the reverse side hereof", normalFont));
Can also create font like
Font verdanaBold = FontFactory.GetFont("Verdana", 7f, Font.BOLD);
Maybe this link Bolding with Rich Text Values in iTextSharp will help?
Not sure if it fits your scenario completely but might get you where you need to go.

Categories