Custom page size in iTextSharp in C#.NET - c#

I want to create a custom page size which is (5"X2") PDF using iTextSharp in C#. Is there any way to do this?
Document doc = new Document(iTextSharp.text.PageSize.A4, 15, 15, 0, 0);

Below code will demonstrate how to implement the custom PDF using PDF coordinates in C#.net. For this task you must aware about the pdf coordinates.
BaseFont f_cn;
string poath = Server.MapPath("~/fonts/CALIBRI.TTF");
f_cn = BaseFont.CreateFont(poath, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
using (System.IO.FileStream fs = new FileStream(Server.MapPath("~/TempPdf") + "\\" + "download.pdf", FileMode.Create))
{
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
Paragraph p = new Paragraph();
// Add meta information to the document
document.AddAuthor("Mikael Blomquist");
document.AddCreator("Sample application using iTestSharp");
document.AddKeywords("PDF tutorial education");
document.AddSubject("Document subject - Describing the steps creating a PDF document");
document.AddTitle("The document title - Amplified Resource Group");
// Open the document to enable you to write to the document
document.Open();
// Makes it possible to add text to a specific place in the document using
// a X & Y placement syntax.
PdfContentByte cb = writer.DirectContent;
cb.SetFontAndSize(f_cb, 16);
// First we must activate writing
cb.BeginText();
// Add an image to a fixed position from disk
iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/arg.png"));
png.SetAbsolutePosition(200, 738);
cb.AddImage(png);
writeText(cb, "Header", 30, 718, f_cb, 14);
}
private void writeText(PdfContentByte cb, string Text, int X, int Y, BaseFont font, int Size)
{
cb.SetFontAndSize(font, Size);
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, Text, X, Y, 0);
}

The document also accept the rectangle type, so we can create a rectangle of our custom size like below.
var pgSize = new iTextSharp.text.Rectangle(1000, 1000);
Document document = new Document(pgSize, 5f, 5f, 20f, 20f);

Related

Insert text in Red Color at the bottom of existing pdf file with itextsharp

I have an existing PDF file, I want to insert a text at the bottom of PDF file in Red color, but the existing pdf file color must remain the same.
Thank You #mkl below code, I used which is specific for Stamp.
public static void ManipulatePdf(string src, string dest)
{
src = #"C:\CCPR Temp\TempFiles\PayStub_000106488_12282019_20200117112403.pdf";
dest = #"C:\CCPR Temp\TempFiles\PayStub_WithStamper.pdf";
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); // create?
int numberOfPages = reader.NumberOfPages;
Rectangle pagesize;
for (int i = 1; i <= numberOfPages; i++)
{
PdfContentByte under = stamper.GetUnderContent(i);
pagesize = reader.GetPageSize(i);
float x =40;// (pagesize.Left + pagesize.Right) / 2;
float y = pagesize.Top/4;// (pagesize.Bottom + pagesize.Top) / 2;
PdfGState gs = new PdfGState();
gs.FillOpacity = 1.0f;
under.SaveState();
under.SetGState(gs);
under.SetRGBColorFill(255,0,0);
ColumnText.ShowTextAligned(under, Element.ALIGN_BOTTOM,
new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 20)),
x, y, 1);
under.RestoreState();
}
stamper.Close();
reader.Close();
}
Adding content to an existing PDF document without changing the existing content, is sometimes referred to as stamping. Examples are adding page numbers, adding a watermark, and adding a running head.
For your specific case:
Create a PdfDocument instance from a PdfReader (to read the input PDF) and a PdfWriter (to write the output PDF). The PdfDocument instance will be in stamping mode.
Set the red text color on a Paragraph with the footer text.
Position the text with the ShowTextAligned convenience method, based on the page size.
You may also want to take into account page rotation.
PdfDocument pdfDoc = new PdfDocument(new PdfReader("input.pdf"), new PdfWriter("output.pdf"));
Document doc = new Document(pdfDoc);
Paragraph footer = new Paragraph("This is a footer").SetFontColor(ColorConstants.RED);
for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
{
Rectangle pageSize = pdfDoc.GetPage(i).GetPageSize();
float x = pageSize.GetLeft() + pageSize.GetWidth() / 2;
float y = pageSize.GetBottom() + 20;
doc.ShowTextAligned(footer, x, y, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0);
}
doc.Close();
This will set the Font of your Paragraph. I am not sure about the Position.
BaseFont btnRedFooter = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font fntRedFooter = FontFactory.GetFont(iTextSharp.text.Font.FontFamily.TIMES_ROMAN.ToString(), 16,
iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.RED);
pProtocoll.Add(new Paragraph("Text in Footer", fntRedFooter));
I used the below steps and finally, got the required output. I was struggling for the font color, to apply to the newly added text.
public static void StampPdfFile(string oldFile, string newFile)
{
// 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.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = $"Voided On - {DateTime.Now.Date.ToString("MM/dd/yyyy")}";
// put the alignment and coordinates here
cb.SetColorFill(BaseColor.RED); //Give Red color to the newly added Text only
cb.ShowTextAligned(2, text, 120, 250, 0);
cb.SetColorFill(BaseColor.BLACK); //Give Red color to the exisitng file content only
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
document.Close();
fs.Close();
writer.Close();
reader.Close();
}

Create a new pdf when the page height exceeded

I'm using iTextSharp 5 to generate a clothing label as a pdf file. I need to create a second pdf rather than creating a new page if the page height is exceeded. Is it possible? How to do this? Please help.
This is my code. I needed to continue this multi language text to an another pdf if it exceeds the page height. Page length is 110 mm. Sometimes multi language text is long.
This is the generated pdf:
protected void btnOpenLabel_Click(object sender, EventArgs e)
{
//BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
//iTextSharp.text.Font titreProgFont = FontFactory.GetFont("HELVETICA", 7, Font.NORMAL,BaseColor.RED);
string fireWarning = "KEEP AWAY FROM FIRE";
string madeinText = "Made in the U.K.";
string sizeuk = "UK";
string multiLanguageText = "This is a long multi language text. This should be continue to next page if the page height exceeded. This should happen automatically when using a very long text in pdfs";
string lastLine = "Edge";
string nextpageText="This text should be placed in next page";
try
{
FileStream fs = new FileStream(Server.MapPath("pdf")+"\\"+ "MnSLabel"+".pdf",FileMode.Create);
float xpointValue = iTextSharp.text.Utilities.MillimetersToPoints(20);
float ypointvalue = iTextSharp.text.Utilities.MillimetersToPoints(110);
Rectangle pageSize = new Rectangle(xpointValue, ypointvalue);
Document document = new Document(pageSize, 0, 0, 3, 0);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.AddAuthor("Chathu");
document.Open();
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
//first text by method calling
iTextSharp.text.Font firewarningFont = FontFactory.GetFont("HELVETICA", 6, Font.NORMAL, BaseColor.RED);
Chunk c1 = new Chunk();
Phrase textPhrase = new Phrase();
ColumnText ct1 = new ColumnText(cb);
SetPDFColumnText(ct1,fireWarning,firewarningFont,c1,textPhrase,4,8,17,90,cb,5,Element.ALIGN_CENTER,Element.ALIGN_CENTER);
//end fire warning by method calling
//made in text method calling
iTextSharp.text.Font madein_textFont = FontFactory.GetFont("HELVETICA",4,Font.NORMAL,BaseColor.BLACK);
SetPDFColumnText(ct1,madeinText,madein_textFont,c1,textPhrase,2,4,18,94,cb,5,Element.ALIGN_CENTER,Element.ALIGN_CENTER);
//end made in method calling
//sizes uk
iTextSharp.text.Font sizeUKFont = FontFactory.GetFont("HELVETICA", 4, Font.NORMAL, BaseColor.BLACK);
SetPDFColumnText(ct1,sizeuk,sizeUKFont,c1,textPhrase,5,45,15,84,cb,1,Element.ALIGN_CENTER,Element.ALIGN_CENTER);
//end size uk
SetPDFColumnText(ct1, multiLanguageText , sizeUKFont, c1, textPhrase, 0, 2, 20, 1, cb, 1, Element.ALIGN_CENTER, Element.ALIGN_CENTER);
cb.EndText();
//care symbols start
PdfReader bgReader = new PdfReader(Server.MapPath("attachments") + "\\" + "CL1.pdf");
PdfImportedPage bg = writer.GetImportedPage(bgReader, 1);
float Scale = 0.25f;
cb.AddTemplate(bg, Scale, 0, 0, Scale, 2, 130);
//care symbols end
//FIBER content
document.Close();
writer.Close();
fs.Close();
lblSuccess.Text = "Sample M&S Label saved to folder";
}
catch (Exception ex)
{
lblSuccess.Text = ex.Message;
}
}
public void SetPDFColumnText(ColumnText ct, string pdfText, iTextSharp.text.Font pdfFont,Chunk pdfChunk,Phrase pdfPhrase,float lowerleft_x,float lowerleft_y,float upperright_x,float upperright_y,PdfContentByte cb,float textLeading,int lineAlignment,int textAlignment) {
float edge_lowerLeftY = 4;
float edge_upperRightY = 2;
int pdfCounter = 1;
edge_lowerLeftY = iTextSharp.text.Utilities.MillimetersToPoints(edge_lowerLeftY);
edge_upperRightY = iTextSharp.text.Utilities.MillimetersToPoints(edge_upperRightY);
//ColumnText ct1 = new ColumnText(cb);
lowerleft_x = iTextSharp.text.Utilities.MillimetersToPoints(lowerleft_x);
lowerleft_y = iTextSharp.text.Utilities.MillimetersToPoints(lowerleft_y);
upperright_x = iTextSharp.text.Utilities.MillimetersToPoints(upperright_x);
upperright_y = iTextSharp.text.Utilities.MillimetersToPoints(upperright_y);
}

Best way to change fonts in PDF document

At the moment I'm trying to change the fonts used in a PDF document.
I therefore declared rectangles and extract the text using LocationTextExtractionStrategy:
System.util.RectangleJ rect = new System.util.RectangleJ(fX, fY, fWidth, fHeight);
RenderFilter[] rfArea = { new RegionTextRenderFilter(rect) };
ITextExtractionStrategy str = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), rfArea);
string s = PdfTextExtractor.GetTextFromPage(reader, 1, str);
This works as expected, although it's quite complicated to find the right coordinates.
But how do I place the text in a new PDF document at the same starting location fX, fY so I don't break the layout?
I tried it using ColumnText but a multiline text is put one above the other:
Paragraph para = new Paragraph(fLineSpacing, s, font);
para.IndentationLeft = fLineIndentionLeft;
para.SpacingAfter = fSpacingAfter;
para.SpacingBefore = fSpacingBefore;
para.Alignment = iFontAlignment;
PdfContentByte cb = writer.DirectContent;
ColumnText ct = new ColumnText(cb);
ct.SetSimpleColumn(para, fX, fY + fHeight, fWidth + fX, fY, 0f, Element.ALIGN_LEFT);
ct.Go();
What am I missing? Or is there even something simpler? Using my approach I will have to cover the entire page defining lots of rectangles.

Rotate multiline text with Columntext ITextSharp

How do i rotate multiline text in itextsahrp?
I have tried:
float x = 200;
float y = 100;
PdfContentByte cb = stamper.GetOverContent(i);
ColumnText ct = new ColumnText(cb);
ct.SetSimpleColumn(new Phrase(new Chunk("Test \n new", FontFactory.GetFont(FontFactory.HELVETICA, 18, iTextSharp.text.Font.NORMAL))),
x, reader.GetCropBox(i).Height -( y+400),500+x, y, 10, Element.ALIGN_LEFT | Element.ALIGN_TOP);
ct.Go();
ColumnText.ShowTextAligned(
cb, Element.ALIGN_CENTER,
new Phrase(new Chunk("Test \n new", FontFactory.GetFont(FontFactory.HELVETICA, 18, iTextSharp.text.Font.NORMAL))), x, reader.GetCropBox(i).Height-y, 12);
ct.SetSimpleColumn shows multilie text but how do I rotate it?
ColumnText.ShowTextAligned does not show multiline.
I don't have a C# environment on my machines, so I've written an example in Java, named AddRotatedTemplate. I have taken an existing PDF file with the words "Hello World", I've created a template/XObject with some text, and I've added that template/XObject twice using the addTemplate() method (once using only x, y coordinates and once using parameters that rotate the text with PI / 4 grades). As a result, the text added to the template is added twice; see hello_template.pdf).
This is the code:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
// Get canvas for page 1
PdfContentByte cb = stamper.getOverContent(1);
// Create template (aka XOBject)
PdfTemplate xobject = cb.createTemplate(80, 120);
// Add content using ColumnText
ColumnText column = new ColumnText(xobject);
column.setSimpleColumn(new Rectangle(80, 120));
column.addElement(new Paragraph("Some long text that needs to be distributed over several lines."));
column.go();
// Add the template to the canvas
cb.addTemplate(xobject, 36, 600);
double angle = Math.PI / 4;
cb.addTemplate(xobject,
(float)Math.cos(angle), -(float)Math.sin(angle),
(float)Math.cos(angle), (float)Math.sin(angle),
150, 600);
stamper.close();
reader.close();
}
There may be easier ways to define the rotation in other variations of the addTemplate() method, but I'm an engineer and I am so used to using the transformation matrix that I never feel the need or desire to use any other type of method.

add page number to pdf document (itextsharp)

I want to add page numbers to the footer of the itextsharp pdf file.Im generating pdf from html (asp.net repeater).And Im using XMLWorkerHelper to parse the html content.I searched a lot but cant find anything useful to achive this.
You'll have to open the PDF with iTextSharp and add the page numbers yourself. I did something like this a while back, here's my function that might give you a start.
The function adds the current page to the lower left, so you might have to place it somewhere else that fits your needs.
public static byte[] AddPageNumbers(byte[] pdf)
{
MemoryStream ms = new MemoryStream();
// we create a reader for a certain document
PdfReader reader = new PdfReader(pdf);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
// we retrieve the size of the first page
Rectangle psize = reader.GetPageSize(1);
// step 1: creation of a document-object
Document document = new Document(psize, 50, 50, 50, 50);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3: we open the document
document.Open();
// step 4: we add content
PdfContentByte cb = writer.DirectContent;
int p = 0;
Console.WriteLine("There are " + n + " pages in the document.");
for (int page = 1; page <= reader.NumberOfPages; page++)
{
document.NewPage();
p++;
PdfImportedPage importedPage = writer.GetImportedPage(reader, page);
cb.AddTemplate(importedPage, 0, 0);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.BeginText();
cb.SetFontAndSize(bf, 10);
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, +p + "/" + n, 7, 44, 0);
cb.EndText();
}
// step 5: we close the document
document.Close();
return ms.ToArray();
}
Something like this should work:
var sourceFileList = new List<string>();
//add files to merge
int sourceIndex = 0;
PdfReader reader = new PdfReader(sourceFileList[sourceIndex]);
int sourceFilePageCount = reader.NumberOfPages;
Document doc = new Document(reader.GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(destinationFileName, FileMode.Create));
doc.Open();
PdfImportedPage page;
PdfContentByte contentByte = writer.DirectContent;
int rotation;
while (sourceIndex < sourceFileList.Count)
{
int pageIndex = 0;
while (pageIndex < sourceFilePageCount)
{
pageIndex++;
doc.SetPageSize(reader.GetPageSizeWithRotation(pageIndex));
doc.NewPage();
page = writer.GetImportedPage(reader, pageIndex);
rotation = reader.GetPageRotation(pageIndex);
if (rotation.Equals(90 | 270))
contentByte.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageIndex).Height);
else
contentByte.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
sourceIndex++;
if (sourceIndex < sourceFileList.Count)
{
reader = new PdfReader(sourceFileList[sourceIndex]);
sourceFilePageCount = reader.NumberOfPages;
}
}
doc.Close();

Categories