Unable to Set PDF text colour with Itextsharp and c# - 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();

Related

iTextSharp–Add header/footer to PDF

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();

ItextSharp Columntext in my PDF

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();

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();
}
}

Add absolute position text to pdf in memorystream

I need to add text to the lower right corner of a pdf. I was able to successfully do this with an annotation but I couldn't flatten it so I attempted to add the text via a paragraph instead. Now none of my text is showing up. Could anyone point out where I'm going wrong with my code below? (Or maybe just tell me how to flatten an annotation... the commented out portion works fine I just need it flattened)
private MemoryStream AddPageNumbers(MemoryStream stream)
{
MemoryStream ms = new MemoryStream();
PdfStamper Stamper = null;
PdfReader Reader = new PdfReader(stream);
try
{
PdfCopyFields Copier = new PdfCopyFields(ms);
Copier.AddDocument(Reader);
Copier.Close();
PdfReader docReader = new PdfReader(ms.ToArray());
ms = new MemoryStream();
Stamper = new PdfStamper(docReader, ms);
for (int i = 1; i <= Reader.NumberOfPages; i++)
{
//iTextSharp.text.Rectangle newRectangle = new iTextSharp.text.Rectangle(315, 19, 560, 33);
//var pcb = new iTextSharp.text.pdf.PdfContentByte(Stamper.Writer);
//string PageNumber = "Confirmation of Completion Report " + i.ToString() + " of " + Reader.NumberOfPages.ToString();
//FontFactory.RegisterDirectories();
//Font fontNormalArial = new Font(FontFactory.GetFont("Arial", 8f, Font.NORMAL));
//Paragraph para = new Paragraph(PageNumber, fontNormalArial);
//var annot = iTextSharp.text.pdf.PdfAnnotation.CreateFreeText(Stamper.Writer, newRectangle, para.Content, pcb);
//annot.Flags = iTextSharp.text.pdf.PdfAnnotation.FLAGS_PRINT;
//annot.BorderStyle = new iTextSharp.text.pdf.PdfBorderDictionary(0, 0);
//Stamper.AddAnnotation(annot, i);
//Stamper.FreeTextFlattening = true;
//Stamper.FormFlattening = true;
PdfContentByte cb = new PdfContentByte(Stamper.Writer);
string PageNumber = "Confirmation of Completion Report " + i.ToString() + " of " + Reader.NumberOfPages.ToString();
FontFactory.RegisterDirectories();
Font fontNormalArial = new Font(FontFactory.GetFont("Arial", 10, Font.NORMAL));
Paragraph para = new Paragraph(PageNumber, fontNormalArial);
para.Alignment = Element.ALIGN_RIGHT;
ColumnText ct = new ColumnText(cb);
ct.AddText(para);
ct.SetSimpleColumn(315, 19, 560 , 38);
ct.SetIndent(316, false);
ct.Go();
}
}
catch (Exception ex)
{
string querystring = "?error=" + ex.Message.ToString();
Response.Redirect("~/ErrorPage.aspx" + querystring);
}
finally
{
if (Stamper != null)
{
Stamper.Close();
}
}
return ms;
}

ITextSharp insert text to an existing pdf

The title sums it all.
I want to add a text to an existing PDF file using iTextSharp, however i can't find how to do it anywhere in the web...
PS: I cannot use PDF forms.
I found a way to do it (dont know if it is the best but it works)
string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
I hope this can be usefull for someone =) (and post here any errors)
In addition to the excellent answers above, the following shows how to add text to each page of a multi-page document:
using (var reader = new PdfReader(#"C:\Input.pdf"))
{
using (var fileStream = new FileStream(#"C:\Output.pdf", FileMode.Create, FileAccess.Write))
{
var document = new Document(reader.GetPageSizeWithRotation(1));
var writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
for (var i = 1; i <= reader.NumberOfPages; i++)
{
document.NewPage();
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
var importedPage = writer.GetImportedPage(reader, i);
var contentByte = writer.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 12);
var multiLineString = "Hello,\r\nWorld!".Split('\n');
foreach (var line in multiLineString)
{
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
}
contentByte.EndText();
contentByte.AddTemplate(importedPage, 0, 0);
}
document.Close();
writer.Close();
}
}
This worked for me and includes using OutputStream:
PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
Rectangle size = reader.GetPageSizeWithRotation(1);
using (Stream outStream = Response.OutputStream)
{
Document document = new Document(size);
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
document.Open();
try
{
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
try
{
cb.SetFontAndSize(BaseFont.CreateFont(), 12);
cb.SetTextMatrix(110, 110);
cb.ShowText("aaa");
}
finally
{
cb.EndText();
}
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
}
finally
{
document.Close();
writer.Close();
reader.Close();
}
}
Here is a method that uses stamper and absolute coordinates showed in the different PDF clients (Adobe, FoxIt and etc. )
public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
{
//variables
string pathin = inputPdfPath;
string pathout = outputPdfPath;
//create PdfReader object to read from the existing document
using (PdfReader reader = new PdfReader(pathin))
//create PdfStamper object to write to get the pages from reader
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
{
//select two pages from the original document
reader.SelectPages("1-2");
//gettins the page size in order to substract from the iTextSharp coordinates
var pageSize = reader.GetPageSize(1);
// PdfContentByte from stamper to add content to the pages over the original content
PdfContentByte pbover = stamper.GetOverContent(1);
//add content to the page using ColumnText
Font font = new Font();
font.Size = 45;
//setting up the X and Y coordinates of the document
int x = point.X;
int y = point.Y;
y = (int) (pageSize.Height - y);
ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
}
}
Here is a method To print over images:
taken from here.
Use a different layer for your text you're putting over the images, and also make sure to use the GetOverContent() method.
string oldFile = "FileWithImages.pdf";
string watermarkedFile = "Layers.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader(oldFile);
using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
// Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
// Getting total number of pages of the Existing Document
int pageCount = reader1.NumberOfPages;
// Create New Layer for Watermark
PdfLayer layer = new PdfLayer("Layer", stamper.Writer);
// Loop through each Page
for (int i = 1; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader1.GetPageSize(i);
// Get the ContentByte object
PdfContentByte cb = stamper.GetOverContent(i);
// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.RED);
cb.SetFontAndSize(bf, 100);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Some random blablablabla...", rect.Width / 2, rect.Height / 2, - 90);
cb.EndText();
// Close the layer
cb.EndLayer();
}
}

Categories

Resources