I know this question has been asked a thousand times, but I am yet to find a straight forward answer. I am relatively new to ITextSharp, so please explain as if you were talking to a toddler. How can I add a simple text only header and footer to the document I am creating?
I am creating a simple pdf document with the following code:
void Button1Click(object sender, EventArgs e)
{
Document doc = new Document(iTextSharp.text.PageSize.LEDGER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(#"File Path", FileMode.Create));
doc.Open();
Paragraph par1 = new Paragraph("Hello World!");
doc.Add(par1);
//Code to add header/footer
doc.Close();
MessageBox.Show("Your PDF has been created!");
}
I have done a lot of research on how to add headers and footers, but they all have to do with complicated page events. Is there an easier way? If there isn't, can you walk me through the process step by step? I would really appreciate any help that you all can give. Thanks!
You are creating your Document like this:
Document doc = new Document(iTextSharp.text.PageSize.LEDGER, 10, 10, 42, 35);
This means that you have a top margin of 42 user units and a bottom margin of 35 user units. You can use this margin to add extra content in a page event.
The official web site has plenty of examples and a comprehensive Q&A section. All examples and answers are tagged. If you click on the header tag, you can find plenty of examples.
As already indicated by others in the comments, you need to create a PdfPageEvent implementation. The easiest way to do this, is by extending the PdfPageEventHelper class.
class MyHeaderFooterEvent : PdfPageEventHelper {
Font FONT = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
public override void OnEndPage(PdfWriter writer, Document document) {
PdfContentByte canvas = writer.DirectContent;
ColumnText.ShowTextAligned(
canvas, Element.ALIGN_LEFT,
new Phrase("Header", FONT), 10, 810, 0
);
ColumnText.ShowTextAligned(
canvas, Element.ALIGN_LEFT,
new Phrase("Footer", FONT), 10, 10, 0
);
}
}
Important to know:
It is forbidden to add content in the OnStartPage() event. Add your header and footer when all the content has been added to the page just before iTextSharp moves to a new page. More specifically: add content in the OnEndPage() event.
It is forbidden to add content to the Document object that is passed to the event. This object can be used for read-only purposes only.
If you examine the OnEndPage() method in the MyHeaderFooterEvent class, you see that we get the DirectContent from the writer and that we add content to this canvas using ShowTextAligned methods. There are many other ways to add content, but you explicitly asked for the easiest way. This way has its limitations, but it's easy.
I used a couple of hard-coded values: I used 10 as the x value for the header and the footer. That's because you defined a left margin of 10 user units. The header and footer are left aligned with the actual content you're adding to the page. I used 810 for the y value of the header because you're creating an A4 page with a top margin of 42. The top y coordinate of your page is 842. The top y coordinate of the top margin is 842 - 42 = 800. I added 10 user units so that your header isn't glued to the actual content. The bottom y coordinate of the page is 0 in your case and the bottom y coordinate of the margin in 35. I used 10 for the base line of the footer.
You created wri and right after creating this PdfWriter instance, you open the Document instance. For the page event to take effect, you should add the following link, right before opening the Document:
wri.PageEvent = new MyHeaderFooterEvent();
Now the OnEndPage() method will be invoked every time your main process finalizes a page.
Important: you added //Code to add header/footer at the wrong place. iTextSharp will try to flush the content of a page as soon as possible. If you add code to add a header/footer after you've added content, you can not go back to add a header and footer to pages that were already flushed to the output stream.
Related
I have working iTextsharp code for printing labels. Now the problem is, I have a requirement to print the labels in Continuous paper which i am not able to select in iTextsharp configuration (iTextSharp.text.PageSize.A4). Please advice how can i select the page size according to my current scenario.
Thanks
Your problem is related to PDF as a document format. In PDF, the content is distributed over different pages. You can define the size of such a page yourself. You mention iTextSharp.text.PageSize.A4, but you can define the page size as a Rectangle object yourself. See iTextsharp landscape document
If you want a long, narrow page, you could define the page size like this:
Document Doc = new Document(new Rectangle(595f, 14400f));
There are some implementation limits though. The maximum height or width of a page is 14,400 user units. See the blog post Help, I only see blank pages in my PDF!
However, I am pretty sure that you don't want to create a long narrow page. If you want to print labels on "continuous paper", you want to create a PDF document in which every page has the size of exactly one label. Your PDF will have as many pages as there are labels.
Suppose that the size of one label is 5 by 2 inch (width: 12.7cm; height: 5.08cm), then you should create a document like this:
Document Doc = new Document(new Rectangle(360, 144));
And you should make sure that all the content of a label fits on a single page. Your label printer should know that each page in the PDF should be printed on a separate label.
(Thank you #amedeeVanGasse for correcting my initial answer.)
I'm using iText 7 with C# and I have to write a long line.
With canvas.BeginText().ShowText("My text") I can't find a way to make the text pass on a second line, \n is not recognized.
So I used rectangles and document renderer but I have the same problem, I can't control where I want my text to create a new line.
I use an existing PDF (a model) where I have to write some texts (as short as a single line) and some paragraphs (composed of several lines). Those elements are defined in an xml where I can have some carriage returns to delimit new lines in paragraphs. Is short, the document is composed dynamically and it's content and element's placement are defined inside an xml file.
Adding content with low-level methods such as BeginText(), ShowText(), EndText() and so on, requires a sound knowledge of the PDF specification (ISO 32000). The fact that you are surprised at the fact that \n is ignored tells me that you aren't that well versed in PDF.
iText was written for people who don't want to deal with the low-level syntax of PDF. For instance: if you want to add text inside a rectangle with iText, you just have to create a Canvas object to which you pass a Rectangle object:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfPage page = pdf.AddNewPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle rectangle = new Rectangle(36, 650, 100, 100);
Canvas canvas = new Canvas(pdfCanvas, pdf, rectangle);
PdfFont font = PdfFontFactory.CreateFont(FontConstants.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.CreateFont(FontConstants.TIMES_BOLD);
Text title =
new Text("The Strange Case of Dr. Jekyll and Mr. Hyde").SetFont(bold);
Text author = new Text("Robert Louis Stevenson").SetFont(font);
Paragraph p = new Paragraph().Add(title).Add(" by ").Add(author);
canvas.Add(p);
pdf.Close();
This example can be found in chapter 2 of the online iText 7 tutorial.
The screenshot shows how a long sentence was added inside a Rectangle, and how that sentence got distributed over different lines (introducing new lines automatically). The concept of the \n character doesn't exist in PDF (check ISO 32000 when in doubt). If you want to introduce a newline, it's sufficient to put one part of the content in one Paragraph and the other part in another Paragraph.
I am using itextsharp to generate pdf ...i m getting problem is my content/text coming upon footer...i want to automatically break down content to new page...if it comes upon footer..
right now i m using document.newpage()
but i want to do it automatically that my page /content automatically breakdown to new page..it should not come to header/footer of page...
FOr Information i create header/footer through this class
public class ITextEvents : PdfPageEventHelper
and i used this function
public override void OnEndPage
I m attaching also the result that i m getting right now...
please help me on this...i can share more information if you ask in comments
i want this last box to come automatically to new page.....
Assuming that you are adding the flowing content using document.add(), you have to make sure that you define a bottom margin that is sufficiently large to accommodate the footer.
You don't share the code you have in your OnEndPage method, but suppose that you have something like:
canvas.MoveTo(36, 50);
canvas.LineTo(559, 50);
canvas.Strike();
This draws a line from x = 36 to x = 559 at y = 50.
Suppose you have created your Document like this:
Document document = new Document();
In this case, you are creating a document with pages in the A4 format (595 x 842 user units) and margins of 36 user units. As the bottom margin is only 36 user units, your content risks overlapping with the line drawn at 50 user units from the bottom.
You should change the line where you create the Document like this:
Document document = new Document(PageSize.A4, 36, 36, 36, 55);
Now you have a bottom margin of 55 user units and the line you draw at 50 user units no longer overlaps.
Note: I use the term user units because that's how we define measurements in PDF. By default 1 user unit equals 1 point. The default margin is 36 user units or half an inch.
Using the below code pdf stamping is working fine but if the pdf page does not have header info or body is empty then stamping is not working I mean pdfData.ShowText(strCustomMessage) is not working.
//create pdfreader object to read sorce pdf
PdfReader pdfReader=new PdfReader(Server.MapPath("Input") + "/" + "input.pdf");
//create stream of filestream or memorystream etc. to create output file
FileStream stream = new FileStream(Server.MapPath("Output") + "/output.pdf", FileMode.OpenOrCreate);
//create pdfstamper object which is used to add addtional content to source pdf file
PdfStamper pdfStamper = new PdfStamper(pdfReader,stream);
//iterate through all pages in source pdf
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
//Rectangle class in iText represent geomatric representation... in this case, rectanle object would contain page geomatry
Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
//pdfcontentbyte object contains graphics and text content of page returned by pdfstamper
PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);
//create fontsize for watermark
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40);
//create new graphics state and assign opacity
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.4F;
//set graphics state to pdfcontentbyte
pdfData.SetGState(graphicsState);
//set color of watermark
pdfData.SetColorFill(BaseColor.BLUE);
//indicates start of writing of text
pdfData.BeginText();
//show text as per position and rotation
pdfData.SetTextMatrix(pageRectangle.Width/2,pageRectangle.Height/2); pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9);
string strCustomMessage="PDF Stamping Test"
pdfData.ShowText(strCustomMessage);
//call endText to invalid font set
pdfData.EndText();
}
//close stamper and output filestream
pdfStamper.Close();
stream.Close();
I think your question is wrong. Would do you mean when you say "the pdf page does not have header info or body is empty"? Because that doesn't make sense.
A few observations: I think you're using an obsolete version of iTextSharp. Read the FAQ to find out why this is a bad idea.
Newer versions of iTextSharp will throw an exception because of this error:
pdfData.BeginText();
//show text as per position and rotation
string strCustomMessage="PDF Stamping Test"
pdfData.ShowText(strCustomMessage);
//call endText to invalid font set
pdfData.EndText();
In these lines, you are violating the PDF reference: you are showing text within a BT/ET sequence without defining a font and size. Had you used a newer version of iTextSharp, an exception would have pointed that out. You need to move the line with the SetFontAndSize() method inside the BeginText()/EndText() sequence. It's illegal to use it outside a text object.
Also: why are you using BeginText()/EndText() to add text? That is code for PDF specialists. Read the documentation to find out how to use ColumnText.ShowTextAligned(). The ShowTextAligned() method is a convenience method written for developer who aren't fluent in PDF syntax.
Whether or not the text added with ShowText() is visible will depend on:
the opacity of the page: Suppose that your page consists of a scanned image, you won't see any text, because you're adding the text under the image. Use the GetOverContent() method instead of the GetUnderContent() method to avoid this.
the position on the page: I see that you get the size of the page using the GetPageSizeWithRotation() method, but I don't see you doing anything with that info. I don't see at which coordinate you are showing the text. That is also wrong. You need to make sure that you add the text inside the visible area of the page.
This answer lists several problems with your code. It would be better if you simplify your code by using the ShowTextAligned() and correct X,Y coordinates.
I am trying to create a pdf document in c# using iTextSharp 5.0.6. I want to add header and footer to every page in OnStartPage and OnEndPage events respectively.
In case of footer there is a problem that the footer is created right where the page ends whereas I would like to be at the bottom of page.
Is there a way in iTextSharp to specify page height so that footer is always created at the bottom.
Thanks!
The page's height is always defined:
document.PageSize.Height // document.getPageSize().getHeight() in Java
Keep in mind that in PDF 0,0 is the lower left corner, and coordinates increase as you go right and UP.
Within a PdfPageEvent you need to use absolute coordinates. It sounds like you're either getting the current Y from the document, or Just Drawing Stuff at the current location. Don't do that.
Also, if you want to use the same exact footer on every page, you can draw everything into a PdfTemplate, then draw that template into the various pages on which you want it.
PdfTemplate footerTmpl = writer.getDirectContent().createTemplate( 0, 0, pageWidth, footerHeight );
footerTmpl.setFontAndSize( someFont, someSize );
footerTmpl.setTextMatrix( x, y );
footer.showText("blah");
// etc
Then in your PdfPageEvent, you can just add footerTempl at the bottom of your page:
writer.getDirectContent().addTemplateSimple( footerTmpl, 0, 0 );
Even if most of your footer is the same, you can use this technique to save memory, execution time, and file size.
Furthermore, if you don't want to mess with PdfContentByte drawing commands directly, you can avoid them to some extent via ColumnText. There are several SO questions tagged with iText or iTextSharp dealing with that class. Poke around, you'll find them.