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);
}
Related
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();
}
When saving, the image has the right design but the PDF has the wrong text on it. Could you explain why the documents are different?
I'm also open to other solutions for saving a PDF of the whole document and the ability to print a selected page of a multi-page document.
thanks :)
EDIT: the image is showing the date ("24th May 2016") which is correct and what I want the PDF to show, but instead the PDF is showing "TEST TEST"
1
public static void pdf() {
DateTime now = DateTime.Now;
string filename = "MixMigraDocAndPdfSharp.pdf";
filename = Guid.NewGuid().ToString("D").ToUpper() + ".pdf";
PdfDocument document = new PdfDocument();
SamplePage1(document);
document.Save(filename);
Process.Start(filename);
}
2
static void SamplePage1(PdfDocument document) {
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.MUH = PdfFontEncoding.Unicode;
gfx.MFEH = PdfFontEmbedding.Default;
XFont font = new XFont("Verdana", 13, XFontStyle.Bold);
gfx.DrawString("TEST TEST", font, XBrushes.Black,
new XRect(100, 100, page.Width - 200, 300), XStringFormats.Center);
Document doc = new Document();
Section sec = doc.AddSection();
Paragraph para = sec.AddParagraph();
header("24th May 2016");
DocumentRenderer docRenderer = new DocumentRenderer(doc);
docRenderer.PrepareDocument();
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", para);
PageInfo info = docRenderer.FormattedDocument.GetPageInfo(1);
int dpi = 150;
int dx, dy;
if (info.Orientation == PdfSharp.PageOrientation.Portrait) {
dx = (int)(info.Width.Inch * dpi);
dy = (int)(info.Height.Inch * dpi);
} else {
dx = (int)(info.Height.Inch * dpi);
dy = (int)(info.Width.Inch * dpi);
}
Image image = new Bitmap(dx, dy, PixelFormat.Format32bppRgb);
Graphics graphics = Graphics.FromImage(image);
graphics.Clear(System.Drawing.Color.White);
float scale = dpi / 72f;
graphics.ScaleTransform(scale, scale);
gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point));
docRenderer.RenderPage(gfx, 1);
gfx.Dispose();
image.Save("test.png", ImageFormat.Png);
doc.BindToRenderer(docRenderer);
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", para);
Process.Start("mspaint", "test.png");
}
3
public static void header(String date) {
Paragraph paragraph = new Paragraph();
var dateIssued = firstPage.AddTextFrame();
dateIssued.Height = "1.0cm";
dateIssued.Width = "6.0cm";
dateIssued.Left = "2.1cm";
dateIssued.RelativeHorizontal = RelativeHorizontal.Margin;
dateIssued.Top = "3.55cm";
dateIssued.RelativeVertical = RelativeVertical.Page;
paragraph = dateIssued.AddParagraph(date);
}
You call docRenderer.RenderPage(gfx, 1); for the image only. This renders the header.
You do not call docRenderer.RenderPage(gfx, 1); for the PDF. So no date there, just the "TEST TEST" you draw earlier.
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();
I am trying to create Landscape PDF using iTextSharp but It is still showing portrait. I am using following code with rotate:
Document document = new Document(PageSize.A4, 0, 0, 150, 20);
FileStream msReport = new FileStream(Server.MapPath("~/PDFS/") + "Sample1.pdf", FileMode.Create);
try
{
// creation of the different writers
PdfWriter writer = PdfWriter.GetInstance(document, msReport);
document.Open();
PdfPTable PdfTable = new PdfPTable(1);
PdfTable.SpacingBefore = 30f;
PdfPCell PdfPCell = null;
Font fontCategoryheader = new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK);
for (int i = 0; i < 20; i++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk("Sales Manager: ", fontCategoryheader)));
PdfPCell.BorderWidth = 0;
PdfPCell.HorizontalAlignment = Element.ALIGN_LEFT;
if (i % 2 == 0)
PdfPCell.BackgroundColor = Color.LIGHT_GRAY;
PdfPCell.PaddingBottom = 5f;
PdfPCell.PaddingLeft = 2f;
PdfPCell.PaddingTop = 4f;
PdfPCell.PaddingRight = 4f;
PdfTable.AddCell(PdfPCell);
}
document.Add(PdfTable);
document.NewPage();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
finally
{
// we close the document
document.Close();
}
Please suggest solution.
Thanks.
Try this
Document Doc = new Document(new Rectangle(288f, 144f), 10, 10, 10, 10);
Doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
you might also need this to expand a table to max width.
var _pdf_table = new PdfPTable(2); // table with two columns
PdfPCell hc = new PdfPCell();
_pdf_table.WidthPercentage = 100; //table width to 100per
_pdf_table.SetTotalWidth(new float[] { 25, iTextSharp.text.PageSize.A4.Rotate().Width - 25 });// width of each column
You must make sure that when setting the page size you do it before a call to Doc.Open();
Regards.
No need to initialize the Document and reset the page size...
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);
...will do the trick.
(4.1.6.0)
I am trying to show the page number of my PDF pages, but I don`t want to show it on first and last pages, because they are covers.
I use this code:
public class PDFPage : iTextSharp.text.pdf.PdfPageEventHelper
{
//I create a font object to use within my footer
protected iTextSharp.text.Font footer
{
get
{
// create a basecolor to use for the footer font, if needed.
iTextSharp.text.Color grey = new iTextSharp.text.Color(40, 40, 40);
Font font = FontFactory.GetFont("Arial", 16, iTextSharp.text.Font.BOLD, grey);
return font;
}
}
//override the OnPageEnd event handler to add our footer
public override void OnEndPage(PdfWriter writer, Document doc)
{
if (doc.PageNumber > 1)
{
//I use a PdfPtable with 2 columns to position my footer where I want it
PdfPTable footerTbl = new PdfPTable(2);
//set the width of the table to be the same as the document
footerTbl.TotalWidth = doc.PageSize.Width;
//Center the table on the page
footerTbl.HorizontalAlignment = Element.ALIGN_CENTER;
//Create a paragraph that contains the footer text
Paragraph para = new Paragraph(" ", footer);
//add a carriage return
para.Add(Environment.NewLine);
para.Add(" ");
//create a cell instance to hold the text
PdfPCell cell = new PdfPCell(para);
//set cell border to 0
cell.Border = 0;
//add some padding to bring away from the edge
cell.PaddingLeft = 10;
//add cell to table
footerTbl.AddCell(cell);
//create new instance of Paragraph for 2nd cell text
para = new Paragraph(" " + doc.PageNumber, footer);
//create new instance of cell to hold the text
cell = new PdfPCell(para);
//align the text to the right of the cell
cell.HorizontalAlignment = Element.ALIGN_LEFT;
//set border to 0
cell.Border = 0;
// add some padding to take away from the edge of the page
cell.PaddingRight = 10;
//add the cell to the table
footerTbl.AddCell(cell);
//write the rows out to the PDF output stream.
footerTbl.WriteSelectedRows(0, -1, 0, (doc.BottomMargin + 25), writer.DirectContent);
}
}
}
Thank you!
(writer.PageNumber - 1) is the last page. so check that too.
public class PageEventHelper : PdfPageEventHelper
{
PdfContentByte cb;
PdfTemplate template;
private int TotalNumber = 0;
//for remeber lastpage
public void SetNumber(int num)
{
TotalNumber = num;
}
public override void OnOpenDocument(PdfWriter writer, Document document)
{
cb = writer.DirectContent;
template = cb.CreateTemplate(50, 50);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
cb = writer.DirectContent;
template = cb.CreateTemplate(50, 50);
BaseFont font = BaseFont.CreateFont();
int pageN = writer.PageNumber;
String text = pageN.ToString();
float len = font.GetWidthPoint(text, 9);
iTextSharp.text.Rectangle pageSize = document.PageSize;
// cb.SetRGBColorFill(100, 100, 100);
;
cb.BeginText();
cb.SetFontAndSize(font, 9);
cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin));
//cb.ShowText(text);
if (pageN > 1 && TotalNumber==0)
{
cb.ShowTextAligned(Element.ALIGN_CENTER, (pageN - 6).ToString() , 300f, 10f, 0);
}
cb.EndText();
cb.AddTemplate(template, document.LeftMargin + len, pageSize.GetBottom(document.BottomMargin));
}
}
And how to use the code ?
doc.Open();
//PdfWriter writer = PdfWriter.GetInstance(doc, stream);
PageEventHelper pageEventHelper = new PageEventHelper();
writer.PageEvent = pageEventHelper;
And before doc.closed()
Use the function SetNumber()
pageEventHelper.SetNumber(writer.PageNumber);
doc.Close();
you can use other number instead of the writer.PageNumber but not 0.
Hope this help you!