iTextSharp–Add header/footer to PDF - c#

This is my first question on stackoverflow.
I hope to be welcome.
My question.
I trying to use iTextSharp for create PDF file with header, footer, number of pages and logo.
My code below and my problem is error on this line of my code behind:
pdfDoc.Close();
If I disable this line the PDF file is created but damaged it cannot be opened.
The error is :
Object reference not set to an instance of an object
I really hope in your help.
Create a PDF file:
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
pdffile.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
string imagepath = Server.MapPath("..") + "\\Logo.jpg";
Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 10f, 20f);
using (MemoryStream memoryStream = new MemoryStream())
{
try
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
writer.PageEvent = new Footer();
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.MAGENTA);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
pdfDoc.Add(image);
var cssResolver = new StyleAttrCSSResolver();
var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("style.css"), FileMode.Open));
cssResolver.AddCss(cssFile);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
// Pipelines
PdfWriterPipeline pdfFile = new PdfWriterPipeline(pdfDoc, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdfFile);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.Parse(sr);
pdfDoc.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
}
catch (Exception ex)
{
throw (ex);
}
}
}
}
Add header/footer to PDF
public partial class Footer : PdfPageEventHelper
{
PdfContentByte cb;
PdfTemplate headerTemplate, footerTemplate;
BaseFont bf = null;
DateTime PrintTime = DateTime.Now;
iTextSharp.text.Image image;
private string _header;
public string Header
{
get { return _header; }
set { _header = value; }
}
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
PrintTime = DateTime.Now;
bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb = writer.DirectContent;
headerTemplate = cb.CreateTemplate(100, 100);
footerTemplate = cb.CreateTemplate(50, 50);
}
catch (DocumentException de)
{
//handle exception here
}
catch (System.IO.IOException ioe)
{
//handle exception here
}
}
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer,
iTextSharp.text.Document document)
{
base.OnEndPage(writer, document);
iTextSharp.text.Font baseFontNormal =
new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f,
iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font baseFontBig =
new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f,
iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
Phrase p1Header = new Phrase("testing", baseFontNormal);
PdfPTable pdfTab = new PdfPTable(3);
PdfPCell pdfCell1 = new PdfPCell();
PdfPCell pdfCell2 = new PdfPCell(p1Header);
PdfPCell pdfCell3 = new PdfPCell();
String text = "Page " + writer.PageNumber + " of ";
{
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 12);
cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
}
{
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 12);
cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
Paragraph footer =
new Paragraph("©All Rights Reserved",
FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.ITALIC));
footer.Alignment = Element.ALIGN_RIGHT;
PdfPTable footerTbl = new PdfPTable(1);
footerTbl.TotalWidth = 800;
footerTbl.HorizontalAlignment = Element.ALIGN_CENTER;
PdfPCell cell = new PdfPCell(footer);
cell.Border = 0;
cell.PaddingLeft = 10;
footerTbl.AddCell(cell);
footerTbl.WriteSelectedRows(0, -1, 0, 30, writer.DirectContent);
}
PdfPCell pdfCell4 = new PdfPCell(new Phrase("test", baseFontNormal));
PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
PdfPCell pdfCell6 = new PdfPCell();
PdfPCell pdfCell7 = new PdfPCell(new Phrase("Hour:" + string.Format("{0:t}", DateTime.Now), baseFontBig));
pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell4.Colspan = 3;
pdfCell1.Border = 0;
pdfCell2.Border = 0;
pdfCell3.Border = 0;
pdfCell4.Border = 0;
pdfCell5.Border = 0;
pdfCell6.Border = 0;
pdfCell7.Border = 0;
pdfTab.AddCell(pdfCell1);
pdfTab.AddCell(pdfCell2);
pdfTab.AddCell(pdfCell3);
pdfTab.AddCell(pdfCell4);
pdfTab.AddCell(pdfCell5);
pdfTab.AddCell(pdfCell6);
pdfTab.AddCell(pdfCell7);
pdfTab.TotalWidth = document.PageSize.Width - 80f;
pdfTab.WidthPercentage = 70;
pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
cb.MoveTo(40, document.PageSize.Height - 100);
cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
cb.Stroke();
cb.MoveTo(40, document.PageSize.GetBottom(50));
cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
cb.Stroke();
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
headerTemplate.BeginText();
headerTemplate.SetFontAndSize(bf, 12);
headerTemplate.SetTextMatrix(0, 0);
headerTemplate.ShowText((writer.PageNumber - 1).ToString());
headerTemplate.EndText();
footerTemplate.BeginText();
footerTemplate.SetFontAndSize(bf, 12);
footerTemplate.SetTextMatrix(0, 0);
footerTemplate.ShowText((writer.PageNumber - 1).ToString());
footerTemplate.EndText();
}
}

You are welcome "Uncle Vince" !
See this
And try this solution.
I hope I was helpful.
MemoryStream memoryStream = new MemoryStream();
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
pdffile.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
string imagepath = Server.MapPath("..") + "\\Logo.jpg";
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
writer.PageEvent = new Footer();
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.MAGENTA);
pdfDoc.Open();
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
pdfDoc.Add(image);
var cssResolver = new StyleAttrCSSResolver();
var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("style.css"), FileMode.Open));
cssResolver.AddCss(cssFile);
//HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
//Pipelines
PdfWriterPipeline pdfFile = new PdfWriterPipeline(pdfDoc, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdfFile);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
//XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.Parse(sr);
writer.CloseStream = false;
pdfDoc.Close();
memoryStream.Close();

Related

Unable to Set PDF text colour with Itextsharp and c#

I am trying to set text colour of PDF using Itextsharp and c#.
Below is the snippet.
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sourcefilePath);
iTextSharp.text.pdf.PdfReader sReader = new iTextSharp.text.pdf.PdfReader(overlayfilePath);
PdfStamper stamper = new PdfStamper(reader, new FileStream(outputFile, FileMode.Create));
int inputDocumentPages = reader.NumberOfPages;
int overlayDocumentPages = sReader.NumberOfPages;
PdfContentByte background;
for (int i = 1; i <= inputDocumentPages; i++)
{
if (i <= overlayDocumentPages)
{
PdfImportedPage page = stamper.GetImportedPage(sReader, i);
background = stamper.GetUnderContent(i);
background.SetColorFill(BaseColor.RED);
background.Fill();
background.AddTemplate(page, 0, 0);
PdfGState state = new PdfGState();
state.FillOpacity = 0.6f;
state.BlendMode = PdfGState.BM_MULTIPLY;
background.SetGState(state);
background.SaveState();
}
}
stamper.Close();
iTextSharp.text.Font fontNormalBlack = iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Blue));
iTextSharp.text.Font fontNormalBlue = iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black));
Document doc = new Document(PageSize.A4);
string caminho = appPath + "//data//temp//" + Guid.NewGuid().ToString() + ".pdf";
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.Create));
doc.SetMargins(70, 70, 70, 70);
doc.AddCreationDate();
doc.Open();
Paragraph paragrafo = new Paragraph();
paragrafo.Alignment = Element.ALIGN_LEFT;
paragrafo.Add(new Chunk("Name: ", fontNormalBlack));
paragrafo.Add(new Chunk("Paulo Muniz" + "\n\n", fontNormalBlue));
paragrafo.Add(new Chunk("Birthday: ", fontNormalBlack));
paragrafo.Add(new Chunk("24/07" + "\n", fontNormalBlue));
doc.Add(paragrafo);
doc.Close();

header and footer using itextsharp using c#

I am using itextsharp for pdf generation using .net web applications. I have installed the following version of itextsharp using nuget package Install-Package iTextSharp -Version 5.5.10. I have seen the samples and developed
code sample to generate the pdf and it is working. However i am not able to understand or get the header footer been added to the pdf. Here is the sample code i am using
public class Header : PdfPageEventHelper
{
protected Phrase header;
public void setHeader(Phrase header)
{
this.header = header;
}
public void onEndPage(PdfWriter writer, Document document)
{
PdfContentByte canvas = writer.DirectContent;
ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT, header, 559, 806, 0);
}
}
Document pdfReport = null;
MemoryStream msReport = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfReport, msReport);
if (!string.IsNullOrEmpty(HeaderText))
{
Header objHeaderFooter = new Header();
//Here i need to assign the string HeaderText to Header. I dont know how to do it.
}
Please help to know how to assign HeaderText using itextSharp. Most of the developers examples are on java
but i am using .net c#.
You want to assign HeaderText to objHeaderFooter in
if (!string.IsNullOrEmpty(HeaderText))
{
Header objHeaderFooter = new Header();
//Here i need to assign the string HeaderText to Header. I dont know how to do it.
}
Assuming HeaderText to be a string you can do so using the Header method setHeader:
objHeaderFooter.setHeader(new Phrase(HeaderText));
Furthermore, you have to assign objHeaderFooter to your PdfWriter instance:
pdfWriter.PageEvent = objHeaderFooter;
Thus:
if (!string.IsNullOrEmpty(HeaderText))
{
Header objHeaderFooter = new Header();
objHeaderFooter.setHeader(new Phrase(HeaderText));
pdfWriter.PageEvent = objHeaderFooter;
}
Furthermore, whenever you override a method in c#, mark it accordingly as override. In particular in your page event listener, use
public override void onEndPage(PdfWriter writer, Document document)
This is easy to forget, especially when porting java examples because in java the corresponding marker #Override is optional.
Below is the sample code provided by the op.
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=abc.pdf");
Response.Charset = "";
Response.BinaryWrite(getbinary());
Response.End();
public byte[] getbinary()
{
Document pdfReport = null;
pdfReport = new Document(PageSize.A4, 25, 25, 40, 25);
MemoryStream msReport = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfReport, msReport);
pdfReport.Open();
if (!string.IsNullOrEmpty("Header Text"))
{
Header objHeaderFooter = new Header();
objHeaderFooter.SetHeader(new Phrase("Header Text"));
pdfWriter.PageEvent = objHeaderFooter;
}
PdfPTable ptData1 = new PdfPTable(1);
ptData1.SpacingBefore = 8;
ptData1.DefaultCell.Padding = 1;
ptData1.WidthPercentage = 100;
ptData1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
ptData1.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
PdfPCell cell1 = new PdfPCell();
cell1.BorderWidth = 0.001F;
cell1.BackgroundColor = new BaseColor(250, 250, 250);
cell1.BorderColor = new BaseColor(100, 100, 100);
cell1.Phrase = new Phrase("Sample text");
ptData1.AddCell(cell1);
PdfPCell cell = new PdfPCell();
cell.BorderWidth = 0.001F;
cell.BackgroundColor = new BaseColor(200, 200, 200);
cell.BorderColor = new BaseColor(100, 100, 100);
cell.Phrase = new Phrase("test value");
ptData1.AddCell(cell);
pdfReport.Add(ptData1);
pdfReport.Close();
return msReport.ToArray();
}
public class Header : PdfPageEventHelper
{
protected Phrase header;
public void SetHeader(Phrase header)
{
this.header = header;
}
public void onEndPage(PdfWriter writer, Document document)
{
PdfContentByte canvas = writer.DirectContent;
ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT, header, 559, 806, 0);
}
}
May be this could be used as a workaround. Added header as another cell value
Below is the code
if (!string.IsNullOrEmpty(HeaderText))
{
PdfPTable Header = new PdfPTable(1);
Header.SpacingBefore = 8;
Header.DefaultCell.Padding = 1;
Header.WidthPercentage = 100;
Header.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
Header.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
PdfPCell cell1 = new PdfPCell();
cell1.BorderWidth = 0.001F;
cell1.BackgroundColor = new BaseColor(250, 250, 250);
cell1.BorderColor = new BaseColor(100, 100, 100);
cell1.Phrase = new Phrase(HeaderText, fontBold);
Header.AddCell(cell1);
pdfReport.Add(ptDataHeader);
}

Cannot access a non-static member of outer type 'System.Web.UI.Page' via nested type 'PrintToPdf._events'

I have been trying to add an image to all pages using iTextSharp.
According to this web page I need to look into the PdfPageEventHelper of iTextSharp.
It provides a method called OnEndPage that allows such things.
Basically, treat the image as being in the header or footer of the document, and use absolute positioning to put it where you want, instead of just in the flow of the page content.
The below code response with error :
Cannot access a non-static member of outer type 'System.Web.UI.Page'
via nested type 'PrintToPdf._events'
On :
PdfPCell cell2 = new PdfPCell(Image.GetInstance(Server.MapPath(imagepath)));
Is there any way to insert the image in the same way in all pages?
Can you help me ?
Thank you in advance.
class _events : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
PdfPTable table = new PdfPTable(1);
table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
PdfPTable table2 = new PdfPTable(2);
string imagepath = #"Img\Logo.jpg";
PdfPCell cell2 = new PdfPCell(Image.GetInstance(Server.MapPath(imagepath)));
cell2.Colspan = 2;
table2.AddCell(cell2);
PdfPCell cell = new PdfPCell(table2);
table.AddCell(cell);
table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 36, writer.DirectContent);
}
}
private void PdfFiles()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
pnPrint.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
string imagepath = #"Img\Logo.jpg";
Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 10f, 20f);
try
{
_events e = new _events();
PdfWriter pw = PdfWriter.GetInstance(pdfDoc, new FileStream("test.pdf", FileMode.Create));
pw.PageEvent = e;
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
for (int i = 0; i < 5; i++)
{
Image image = Image.GetInstance(Server.MapPath(imagepath));
image.Alignment = Image.ALIGN_LEFT;
pdfDoc.Add(image);
htmlparser.Parse(sr);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
pdfDoc.Close();
Response.End();
}
}
Edit #1
protected class MyEvent : PdfPageEventHelper
{
Image image;
public override void OnOpenDocument(PdfWriter writer, Document document)
{
image = Image.GetInstance(#"C:\\intepub\\wwwroot\\img\\Logo.jpg");
image.SetAbsolutePosition(12, 300);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
writer.DirectContent.AddImage(image);
}
}
// step 1
Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 10f, 20f);
// step 2
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
MyEvent e = new MyEvent();
writer.PageEvent = e;
// step 3
pdfDoc.Open();
// step 4
pdfDoc.Add(new Paragraph("Hello World!"));
// step 5
pdfDoc.Close();

itextsharp pdf not showing

I am using the following code to generate a PDF using iTextSharp from a GridView however the generated PDF is not visible to me. How can I view it in my html page?
GridView1.Visible = false;
SqlConnection sql = Connection.con();
sql.Open();
SqlCommand cmd = new SqlCommand("spGetSalesbyCustomer", sql);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustomerId", Convert.ToInt32(TextBox1.Text));
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dd = new DataTable();
adp.Fill(dd);
GridView2.DataSource = dd;
GridView2.DataBind();
int cellCount = GridView2.Columns.Count;
sql.Close();
if (cellCount > 0)
{
GridView2.AllowPaging = false;
GridView2.DataBind();
BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + #"\fonts\ARIALUNI.TTF", BaseFont.IDENTITY_H, true);
iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(cellCount);
int[] widths = new int[cellCount];
for (int x = 0; x < cellCount; x++)
{
widths[x] = (int)GridView2.Columns[x].ItemStyle.Width.Value;
string cellText = Server.HtmlDecode(GridView2.HeaderRow.Cells[x].Text);
//Set Font and Font Color
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
//font.Color = new Color(GridView2.HeaderStyle.ForeColor);
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));
//Set Header Row BackGround Color
//cell.BackgroundColor = new Color(GridView2.HeaderStyle.BackColor);
table.AddCell(cell);
}
table.SetWidths(widths);
for (int i = 0; i < GridView2.Rows.Count; i++)
{
if (GridView2.Rows[i].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < GridView2.Columns.Count; j++)
{
string cellText = Server.HtmlDecode(GridView2.Rows[i].Cells[j].Text);
//Set Font and Font Color
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
//font.Color = new Color(GridView2.RowStyle.ForeColor);
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));
//Set Color of row
if (i % 2 == 0)
{
//Set Row BackGround Color
//cell.BackgroundColor = new Color(GridView2.RowStyle.BackColor);
}
table.AddCell(cell);
}
}
}
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
int pages = pdfDoc.;
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
Your question is a little unclear but if your code is correct (and I know it isn't 100% based on the seventh last line) then you're not actually adding your PdfPTable to the Document:
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
//Bind a writer to our document abstraction and our output stream
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
//Open the document for writing
pdfDoc.Open();
//This next line is a syntax error
//int pages = pdfDoc.;
//Add the table to the PDF
pdfDoc.Add(table);
//Close the document
pdfDoc.Close();
//ASP.Net/HTTP stuff
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Do not use this next line, it doesn't do what you think it does
//Response.Write(pdfDoc);
Response.End();

Document.NewPage giving object referance not set to an instance of an object

I'm new to creating pdfs, and successfully had one working but no footer, so I've been looking around and based myself on this
This is the code I have of it:
string nome = "MapaAnual" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString() + ".pdf";
string outputFile = "C:\\Users\\sies4578\\Documents\\Visual Studio 2012\\Projects\\ULSM_Equipamentos\\REL\\" + nome.ToString();
try
{
//Create a standard .Net FileStream for the file, setting various flags
//FileStream fs = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
System.IO.FileStream fs = new System.IO.FileStream(outputFile + DateTime.Now.ToString("ddMMyyHHmmss") + ".pdf", System.IO.FileMode.OpenOrCreate);
//Create a new PDF document setting the size to A4
Document doc = new Document(PageSize.A4.Rotate());
//Bind the PDF document to the FileStream using an iTextSharp PdfWriter
PdfWriter w = PdfWriter.GetInstance(doc, fs);
w.PageEvent = new MyPageEventHandler();
//Open the document for writing
doc.Open();
for (int i = 0; i < listaServicos.Count; i++)
{
doc.NewPage(); //where it goes to the catch giving that error
#region Calibracoes
//Code that doesn't matter
#endregion
}
doc.Close();
Process.Start(outputFile);
return "PDF criado com sucesso";
}
catch (Exception ex)
{
Console.WriteLine("An error ocurred, the PDF-document could not be created.");
return ex.Message;
}
I doubt it's related but as asked here is the code of MyPageEventHandler:
public class MyPageEventHandler : iTextSharp.text.pdf.PdfPageEventHelper
{
// This is the contentbyte object of the writer
PdfContentByte cb;
// we will put the final number of pages in a template
PdfTemplate template;
// this is the BaseFont we are going to use for the header / footer
BaseFont bf = null;
// This keeps track of the creation time
DateTime PrintTime = DateTime.Now;
protected iTextSharp.text.Font footer
{
get
{
// create a basecolor to use for the footer iTextSharp.text.Font, if needed.
BaseColor grey = new BaseColor(128, 128, 128);
iTextSharp.text.Font font = iTextSharp.text.FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, grey);
return font;
}
}
public override void OnStartPage(PdfWriter writer, Document doc)
{
//Inicio Cabeçalho Logo
//Inicio Cabeçalho Logo
PdfPTable cabecalho = new PdfPTable(3);
cabecalho.DefaultCell.Border = 0;
cabecalho.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
cabecalho.TotalWidth = 700;
float[] width1 = { 150.0F, 550.0F, 550.0F };
cabecalho.SetWidths(width1);
cabecalho.LockedWidth = true;
iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance("C:\\ULSMatosinhos\\Software\\ULS-Matosinhos\\Images\\logopro.png");
cabecalho.AddCell(im);
iTextSharp.text.Font cabeca = new iTextSharp.text.Font(iTextSharp.text.FontFactory.GetFont("arial", 14, iTextSharp.text.Font.BOLDITALIC, new BaseColor(23, 181, 150)));
PdfPCell linha = new PdfPCell(new Phrase("PLANO DE CALIBRAÇÕES - " + anoCalibracao.ToString(), cabeca));
linha.Border = 0;
linha.HorizontalAlignment = 1;
linha.VerticalAlignment = Element.ALIGN_MIDDLE;
cabecalho.AddCell(linha);
iTextSharp.text.Font cd = new iTextSharp.text.Font(iTextSharp.text.FontFactory.GetFont("arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK));
PdfPCell codigoDoc = new PdfPCell(new Phrase(" 591_00_SIE_1191", cd));
codigoDoc.Border = 0;
codigoDoc.HorizontalAlignment = 1;
codigoDoc.VerticalAlignment = Element.ALIGN_MIDDLE;
cabecalho.AddCell(codigoDoc);
doc.Add(cabecalho);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
int pageN = writer.PageNumber;
String text = "Page " + pageN + " of ";
float len = bf.GetWidthPoint(text, 8);
iTextSharp.text.Rectangle pageSize = document.PageSize;
cb.SetRGBColorFill(100, 100, 100);
cb.BeginText();
cb.SetFontAndSize(bf, 8);
cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30));
cb.ShowText(text);
cb.EndText();
cb.AddTemplate(template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30));
cb.BeginText();
cb.SetFontAndSize(bf, 8);
cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT,
"Printed On " + PrintTime.ToString(),
pageSize.GetRight(40),
pageSize.GetBottom(30), 0);
cb.EndText();
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
template.BeginText();
template.SetFontAndSize(bf, 8);
template.SetTextMatrix(0, 0);
template.ShowText("" + (writer.PageNumber - 1));
template.EndText();
}
}

Categories

Resources