Reputation: 47
I'm trying to write a pdf document with itextsharp but I wont to alternate between two styles: the title and the paragraph.
I tryed something like this:
Paragraph title= new Paragraph();
title.Alignment = Element.ALIGN_CENTER;
title.Font = FontFactory.GetFont("Arial", 32);
title.Add("\nTitle 1\n\n");
pdfDoc.Add(title);
Paragraph paragraph = new Paragraph();
paragraph.Alignment = Element.ALIGN_LEFT;
paragraph.Font = FontFactory.GetFont("Arial", 12);
paragraph.Add("Lorem ipsum dolor sit amet \n");
pdfDoc.Add(paragraph);
title.Add("\nTitle 2\n\n");
pdfDoc.Add(title);
paragraph.Add("Consectetur adipiscing elit \n");
pdfDoc.Add(paragraph);
But it looks like I need to clear the content before adding the new text. Is it possible to clear just the text or would I have to create new variables for each paracgraph? Hope not....
Upvotes: 3
Views: 8075
Reputation: 77546
One way to fix your problem is to change your code like this:
Font titleFont = FontFactory.GetFont("Arial", 32);
Font regularFont = FontFactory.GetFont("Arial", 36);
Paragraph title;
Paragraph text;
title = new Paragraph("Title", titleFont);
title.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(title);
text = new Paragraph("Lorem ipsum dolor sit amet", regularFont);
pdfDoc.Add(text);
title = new Paragraph("Title 2", titleFont);
title.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(title);
text = new Paragraph("Consectetur adipiscing elit", regularFont);
pdfDoc.Add(text);
It would be considered a serious bug if content would disappear after adding text. It would mean that objects that are used once, can no longer be reused. In short: in your question, you are asking the developers of iTextSharp to introduce a bug...
Typically, one creates a separate class defining all the Font
objects that are used. It is also a good idea to create a helper class with custom methods such as getTitle()
, getText()
, etc, similar to the PojoToElementFactory class (note that POJO stands for Plain Old Java Object. The original code was written in Java, by... yours truly).
It is a bad idea to use \n
to introduce newlines. Why aren't you using properties such as the leading, the spacing before and the spacing after to define white space between the lines?
Upvotes: 3