I am creating a PDF file, but have stumbled upon a problem. Below are the iText
commands that are causing it.
document.Header = header;
document.Open();
PdfContentByte cb = writer.DirectContentUnder; (getDirectContentUnder() for java)
document
is of type Document
; writer
is a PdfWriter
and header
is of type HeaderFooter
.
iText
have same conditions for order of those commands and those are:
PdfWriter
cannot be used before opening the document- header of the PDF will not be shown at all, if I open the document before I add the header to it
That would be fine and I would write it in the order just like in the snippet above. But I need the PdfWriter
for creating the header. And now I am in a loop:
- to create the header, I need to use
PdfWriter
- to use
PdfWriter
, I need to open the document first - for the header to be visible, I would need to create it before opening the document
Also, I found sources both for recommending the header to be created as the last thing before opening the document, as well as for recommending the header to be created after the document has been opened. Which is right and how to solve my problem?
Update: Code
BaseFont bf16 = BaseFont.CreateFont( "c:\\windows\\fonts\\Arial.ttf", BaseFont.CP1250, false );
Font fnt10Bold = new Font( bf16, 10, Font.BOLD, new Color( 100, 100, 100 ) );
System.Drawing.Bitmap headerBitmap = Properties.Resources.doc_header;
Image headerImg = Image.GetInstance( headerBitmap, Color.BLACK );
Document document = new Document( PageSize.A4, 36, 40, 20, 20 );
PdfWriter writer = PdfWriter.GetInstance( document, new FileStream( path, FileMode.Create ) );
for ( int i = 0; i < DocList.Count; i++ )
{
PdfPTable tblHeader = new PdfPTable( new float[] { 40, 60 } );
tblHeader.WidthPercentage = 100;
PdfContentByte cb = writer.DirectContentUnder;
Image img = getWatermarkedImage( cb, headerImg, "Watermark", font10Bold );
PdfPCell cellHeader = new PdfPCell( img, true ) { Colspan = 2
HorizontalAlignment = Element.ALIGN_LEFT,
VerticalAlignment = Element.ALIGN_BOTTOM };
tblHeader.AddCell( cellHeader );
Phrase headerPhrase = new Phrase();
headerPhrase.Add( tblHeader );
document.Header = new HeaderFooter( headerPhrase, false );
if ( i == 0 )
document.Open();
else
document.NewPage();
}
document.Close();
getWatermarkedImage
is the method from this answer by Bruno Lowagie.