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);
}
Related
I have 11 grid view in my page I want to export it into single pdf file, I searched this query and implemented the code which I got but it didn't work and generate pdf with black background only headers is showing not the content. Please provide me the code to export all 10 grid views into single pd
protected void btnExportToPDF_Click(object sender, EventArgs e)
{
GridView[] gvpdf = new GridView[] { GV1,GV2,GV3,GV4,GV5,GV6,GV7,GV8,GV9,GV10,GV11};
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
MemoryStream ms = new MemoryStream();
PdfWriter.GetInstance(pdfDoc, ms);
pdfDoc.Open();
for (int i = 0; i < gvpdf.Length; i++)
{
if (gvpdf[i].Visible)
{
PdfPTable pdfTbl = new PdfPTable(gvpdf[i].HeaderRow.Cells.Count);
pdfTbl.SpacingAfter = 20f;
foreach (TableCell headerTblCell in gvpdf[i].HeaderRow.Cells)
{
System.Drawing.Font font = new System.Drawing.Font("Arial", 24, FontStyle.Bold);
font.Color = new BaseColor(gvpdf[i].HeaderStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(headerTblCell.Text));
pdfCell.BackgroundColor = new BaseColor(gvpdf[i].HeaderStyle.ForeColor);
pdfTbl.AddCell(pdfCell);
}
foreach (GridViewRow gvRow in gvpdf[i].Rows)
{
foreach (TableCell tblCell in gvRow.Cells)
{
System.Drawing.Font font = new System.Drawing.Font("Arial", 24, FontStyle.Bold);
font.Color = new BaseColor(gvpdf[i].RowStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(tblCell.Text));
pdfCell.BackgroundColor = new BaseColor(gvpdf[i].RowStyle.ForeColor);
pdfTbl.AddCell(pdfCell);
}
}
pdfDoc.Add(pdfTbl);
}
}
pdfDoc.Close();
byte[] content = ms.ToArray();
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=report_" + ".pdf");
Response.BinaryWrite(content);
Response.Flush();
Response.End();
}
You may want to try another approach. Just read all your data from mentioned grids, store it in POCO classes and then use some library to convert this information into a PDF file with desired formatting.
Personally, I recommend a free and open-source library called QuestPDF (notice, I am its creator). It offers an easy to use fluent API, detailed documentation and a getting started tutorial showing how to generate an invoice document.
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();
I have used Itextsharp from Nuget Package and parsed HTML to PDF and passed Bytes to frontend of website and showing the PDF on iframe.
Firstly i had two separate HTML for the PDF,i.e., one for the header and other one for the body. When i used to parse the HTML to PDF, the issue which came across was the repetition of header. Header is works fine on the first page but on the second page header and body overlap each other. I tried a lot by overriding OnStartPage and OnEndPage function but nothing worked.
Secondly I tried header through C# code and body through HTML but that also seems not be not working and having the same issue.
I think the main issue is with page break(correct me if i am wrong). If any of you from the community can help me out please go forward. I am sharing the code and really appreciate all the help.
Please let me know if any code is missing. I need header on every page that need to be consistent but with dynamic content.
using System;
using System.Collections.Generic;
using iTextSharp.text.html.simpleparser;
namespace WebApi.Controllers
{
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.css;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;
using System.IO;
using System.Text;
using System.Web.Mvc;
public class PDFGenerateController : Controller
{
[NonAction]
public byte[] Index(IModel iModel)
{
// get HTML for body
var html = GetHtml(iModel, false);
byte[] bytes;
Document pdfDocument = new Document(PageSize.A4);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDocument, memoryStream);
AddImageToHeader pageEventHandler = new AddImageToHeader(GetHtml(processedData, true)); // get html for header right side
IHeaderFooter iHeaderFooter = new IHeaderFooter(GetHtml(processedData, true)); // get html for header right side
writer.PageEvent = iHeaderFooter;
writer.PageEvent = pageEventHandler;
writer.PageEvent = new HeaderFooterAdd(iModel);
writer.CloseStream = false;
pdfDocument.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile("C:/pdf.css", true);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext,
new PdfWriterPipeline(pdfDocument, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser xmlParser = new XMLParser(worker);
xmlParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(html)));
pdfDocument.Close();
bytes = memoryStream.GetBuffer();
memoryStream.Close();
}
return bytes;
}
public class iHeaderFooter : PdfPageEventHelper
{
private readonly string _html;
public iHeaderFooter(string html)
{
_html = html;
}
public override void OnStartPage(PdfWriter writer, Document document)
{
var cssResolver = new StyleAttrCSSResolver();
XMLWorkerFontProvider fontProvider =
new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html1 = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html1);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.Parse(new StringReader(_html));
//for page break but didn't worked out
/*using (TextReader htmlViewReader = new StringReader(_html))
{
using (var htmlWorker = new HeaderFooterAdd.HTMLWorkerExtended(document))
{
htmlWorker.Open();
htmlWorker.Parse(htmlViewReader);
}
}*/
base.OnStartPage(writer, document);
}
}
}
// Add logo image to header left side
public class AddImageToHeader : PdfPageEventHelper
{
private readonly string _html;
public AddImageToHeader(string html)
{
_html = html;
}
public override void OnStartPage(PdfWriter writer, Document document)
{
iTextSharp.text.Image imghead = iTextSharp.text.Image.GetInstance("C:/logo.png");
imghead.ScaleAbsolute(189f, 79f);
imghead.SetAbsolutePosition(30, 0);
PdfContentByte cbhead = writer.DirectContent;
PdfTemplate tp = cbhead.CreateTemplate(320, 100);
tp.AddImage(imghead);
cbhead.AddTemplate(tp, 0, 830 - 95);
base.OnStartPage(writer, document);
}
}
public class HeaderFooterAdd : PdfPageEventHelper
{
//C# Header
public override void OnEndPage(PdfWriter writer, Document document)
{
PdfPTable tbHeader = new PdfPTable(2);
tbHeader.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
tbHeader.DefaultCell.Border = Rectangle.NO_BORDER;
tbHeader.DefaultCell.BorderWidth = 0;
tbHeader.DefaultCell.Top = 100;
tbHeader.DefaultCell.Bottom = 100;
tbHeader.AddCell(new Paragraph());
Phrase datePhrase = new Phrase(new Chunk($"{"Label"}: {"Text"}\n", FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL, BaseColor.BLACK)));
PdfPCell _cell = new PdfPCell(datePhrase);
_cell.HorizontalAlignment = Element.ALIGN_RIGHT;
_cell.BorderWidthBottom = 0f;
_cell.BorderWidthLeft = 0f;
_cell.BorderWidthTop = 0f;
_cell.BorderWidthRight = 0f;
_cell.PaddingTop = 45f;
_cell.ExtraParagraphSpace = 2f;
tbHeader.AddCell(_cell);
tbHeader.AddCell(new Paragraph());
tbHeader.WriteSelectedRows(0, -1, document.Left,
writer.PageSize.GetTop(document.TopMargin) + 40,
writer.DirectContent);
}
//for page break but didn't worked out
/*public class HTMLWorkerExtended : HTMLWorker
{
public HTMLWorkerExtended(IDocListener document) :
base(document)
{
}
public override void StartElement(string tag,
IDictionary<string, string> str)
{
if (tag.Equals("newpage"))
document.Add(Chunk.NEXTPAGE);
else
base.StartElement(tag, str);
}
}*/
}
I am trying to export multiple gridviews into single pdf using iTextSharp. I am looping through the gridviews and then looping through the rows of the gridview. The looping is going ok. But after pdf download, only the last gridview can be seen. It seems the gridviews are overwriting each other and only last one remains. Here is my code. What am I doing wrong?
protected void btnExportToPDF_Click(object sender, EventArgs e)
{
GridView[] gvExcel = new GridView[] { gridvw1,gridvw2,gridvw3 };
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
for (int i = 0; i < gvExcel.Length; i++)
{
if (gvExcel[i].Visible)
{
PdfPTable pdfTbl = new PdfPTable(gvExcel[i].HeaderRow.Cells.Count);
foreach (TableCell headerTblCell in gvExcel[i].HeaderRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(headerTblCell.Text));
pdfCell.BackgroundColor = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
pdfTbl.AddCell(pdfCell);
}
foreach (GridViewRow gvRow in gvExcel[i].Rows)
{
foreach (TableCell tblCell in gvRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(gvExcel[i].RowStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(tblCell.Text));
pdfCell.BackgroundColor = new BaseColor(gvExcel[i].RowStyle.ForeColor);
pdfTbl.AddCell(pdfCell);
}
}
//Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(pdfTbl);
}
}
pdfDoc.Close();
//Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=report_" + startDate + "-" + endDate + ".pdf");
Response.Write(pdfDoc);
Response.Flush();
Response.End();
}
One of your errors is not an iText error; it's is a simple logical error that can be solved with common sense. The other error is weird. You aren't using the Response correctly.
protected void btnExportToPDF_Click(object sender, EventArgs e)
{
GridView[] gvExcel = new GridView[] { gridvw1,gridvw2,gridvw3 };
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
MemoryStream ms = new MemoryStream();
PdfWriter.GetInstance(pdfDoc, ms);
pdfDoc.Open();
for (int i = 0; i < gvExcel.Length; i++)
{
if (gvExcel[i].Visible)
{
PdfPTable pdfTbl = new PdfPTable(gvExcel[i].HeaderRow.Cells.Count);
pdfTbl.SpacingAfter = 20f;
foreach (TableCell headerTblCell in gvExcel[i].HeaderRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(headerTblCell.Text));
pdfCell.BackgroundColor = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
pdfTbl.AddCell(pdfCell);
}
foreach (GridViewRow gvRow in gvExcel[i].Rows)
{
foreach (TableCell tblCell in gvRow.Cells)
{
Font font = new Font();
font.Color = new BaseColor(gvExcel[i].RowStyle.ForeColor);
PdfPCell pdfCell = new PdfPCell(new Phrase(tblCell.Text));
pdfCell.BackgroundColor = new BaseColor(gvExcel[i].RowStyle.ForeColor);
pdfTbl.AddCell(pdfCell);
}
}
pdfDoc.Add(pdfTbl);
}
}
pdfDoc.Close();
byte[] content = ms.ToArray();
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=report_" + startDate + "-" + endDate + ".pdf");
Response.BinaryWrite(content);
Response.Flush();
Response.End();
}
There might be some other issues, but I hope you understand the logical error:
You created a new PDF file with PdfWriter every time you entered the loop. You should only create one PdfWriter instance if you only want to create one PDF.
It's better to create the PDF in a MemoryStream, and then write the content of that stream to the Response object as a binary stream. I really didn't understand what you were doing there (and why you tried to do it that way).
I also introduced a SpacingAfter of 20 user units, otherwise it will look as if all tables all glued together into one big table.
There may still be some errors in the way you send the file to the Response, but this should already get you on your way. (Why aren't you sending the file size to the browser? You know that size, don't you? It's the number of bytes in the content object.)
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();