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();
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 am trying to get a pdf from datatable and attach it to an entity in CRM. For that purpose I use this code. Unfortunately created pdf is broken, I am unable to open it. Any ideas?
private static string ExportToBase64Pdf(DataTable dt, string entityName)
{
using (MemoryStream memoryStream = new MemoryStream())
{
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Font font5 = FontFactory.GetFont(FontFactory.HELVETICA, 5);
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[dt.Columns.Count];
for (int i =0; i<dt.Columns.Count; i++) { widths[i] = 4f; }
table.SetWidths(widths);
table.WidthPercentage = 100;
PdfPCell cell = new PdfPCell(new Phrase(entityName));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, font5));
}
foreach (DataRow r in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
table.AddCell(new Phrase(r[i].ToString(), font5));
}
}
document.Add(table);
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
return encodedPDF;
}
}
You retrieve the document bytes before the document is finished by closing:
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
Move the close call before the ToArray call.
i´m working at a little program.
I have a PDF with 17 pages and i want to place columntext on some of them.
But after creating the PDF i get only Page one out.
{
string newfile = "newfile.pdf";
FileStream fs = new FileStream(newfile, FileMode.Create, FileAccess.Write);
PdfReader reader = null;
PdfWriter writer = null;
PdfImportedPage page = null;
Document dc = null;
dc = new Document(reader.GetPageSizeWithRotation(1));
writer = PdfWriter.GetInstance(dc, fs);
dc.Open();
int numberOfPages = reader.NumberOfPages;
PdfContentByte cb = writer.DirectContent;
reader = new PdfReader(pdfPath);
for (int i = 1; i <= numberOfPages; i++)
{
page = writer.GetImportedPage(reader, startPage);
cb.AddTemplate(page, 0, 0);
if (startPage == 1)
{
cb.BeginText();
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase(new Chunk("<<NAME>>", FontFactory.GetFont("c:\\windows\\fonts\\Roboto-BoldCondensed.ttf", 15, BaseColor.BLACK)).SetSkew(0, 10)), 367.7F, 140.7F, 10);
cb.EndText();
}
startPage++;
}
dc.Close();
fs.Close();
writer.Close();
reader.Close();
}
Addition originally posted as answer
I tried to use stamper but the PDF file ist damaged. Something is wrong with my code string newfile = "newfile2.pdf";
FileStream fs = new FileStream(newfile, FileMode.Create, FileAccess.Write);
PdfReader reader = null;
reader = new PdfReader(pdfPath);
PdfStamper stamper = new PdfStamper(reader,fs);
int numberOfPages = reader.NumberOfPages;
PdfContentByte cb;
for (int i = 1; i <= numberOfPages; i++)
{
cb = stamper.GetOverContent(i);
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase(new Chunk("<<NAME>>", FontFactory.GetFont("c:\\windows\\fonts\\Roboto-BoldCondensed.ttf", 15, BaseColor.BLACK)).SetSkew(0, 10)), 367.7F, 140.7F, 10);
}
fs.Close();
reader.Close();
I am trying to get a pdf from datatable and attach it to an entity in CRM. For that purpose I use this code. Unfortunately created pdf is broken, I am unable to open it. Any ideas?
private static string ExportToBase64Pdf(DataTable dt, string entityName)
{
using (MemoryStream memoryStream = new MemoryStream())
{
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Font font5 = FontFactory.GetFont(FontFactory.HELVETICA, 5);
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[dt.Columns.Count];
for (int i =0; i<dt.Columns.Count; i++) { widths[i] = 4f; }
table.SetWidths(widths);
table.WidthPercentage = 100;
PdfPCell cell = new PdfPCell(new Phrase(entityName));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, font5));
}
foreach (DataRow r in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
table.AddCell(new Phrase(r[i].ToString(), font5));
}
}
document.Add(table);
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
return encodedPDF;
}
}
You retrieve the document bytes before the document is finished by closing:
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
Move the close call before the ToArray call.