create PDF file using itextsharp in C# - c#

I have need to create PDF files where draw line on page using margin of left,right and top. But here, confusion due to that, calculation of these margin are in pixel value. So, how can it possible that draw line with setting of margin in pixel value ?
Sample code as below:
PdfContentByte contentByte = writer.DirectContent;
contentByte.SetLineWidth(1);
float x1, y1, x2, y2;
x1 = myDocument.PageSize.Width - 84;
x2 = myDocument.PageSize.Width - 36;
y1 = myDocument.PageSize.Height - 56;
y2 = myDocument.PageSize.Height - 56;
contentByte.MoveTo(x1, y1);
contentByte.LineTo(x2, y2);
contentByte.Stroke();
Actually, i want to draw line of width is 48 which have right margin is 36px, and top margin is 36px.
Have any idea to calculate it ?

Try this way:
string pdfpath = Server.MapPath("PDFs");
Document doc = new Document();
try
{
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Graphics.pdf", FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
...
Now that we have a working PdfContentByte object, we can use it to start drawing:
cb.MoveTo(doc.PageSize.Width / 2, doc.PageSize.Height / 2);
cb.LineTo(doc.PageSize.Width / 2, doc.PageSize.Height);
cb.Stroke();
cb.MoveTo(0, doc.PageSize.Height/2);
cb.LineTo(doc.PageSize.Width, doc.PageSize.Height / 2);
cb.Stroke();
Took from here

Related

Getting past the 200 inch adobe error with iTextSharp

I am converting a multi-paged (paginated) pdf document into a single page (non-paginated) pdf document.
I am looking to overcome the 200 inch limitation in adobe reader.
With iTextSharp.PdfReader each page is read to create a total height of the target document and find the maximum width.
The code to create the document works ok reading directly from the paginated pdf into the non-paginated pdf. Utilizing Chrome or Foxit the file opens fine. Adobe gives the 200 inch truncation when the page exceeds 200 inchs. In my test file the page height is 8.25 x 814 inches.
Changing the UserUnits to 4.07 (814/200) has Adobe show the page height as 814in but still truncates the page as well as showing the width as 33.
If the width of the target file is set to width/userunits (8.25/4.07) the only left 2 inches are shown in the target file.
The copy part of the code:
RandomAccessFileOrArray ra = new RandomAccessFileOrArray(fn);
SizeF pageSize = new SizeF(pageWidth, pageHeight);
float USERUnitNewValue = ComputeUserUnit(pageSize);
if (pageHeight > 14400f)
{
USERUnitNewValue = pageHeight / 14400f;
}
float NewPageWidth = (pageWidth <= 14400f) ? pageWidth : pageWidth* USERUnitNewValue;
float NewPageHeight = pageHeight * USERUnitNewValue;
FileInfo file1 = new FileInfo(newfn);
DirectoryInfo directory1 = file1.Directory;
if (!directory1.Exists)
directory1.Create();
iTextSharp.text.Rectangle newPagesize = new iTextSharp.text.Rectangle(pageWidth, pageHeight);
Document newPdf = new Document(newPagesize);
PdfWriter writer = PdfWriter.GetInstance(newPdf, new FileStream(newfn, FileMode.Create));
writer.PdfVersion = PdfWriter.VERSION_1_6;
if (pageHeight > 14400)
{
writer.Userunit = USERUnitNewValue;
}
newPdf.SetMargins(0f, 0f, 0f, 0f);
newPdf.Open();
PdfContentByte cb = writer.DirectContent;
float verticalPosition = pageHeight;
for (int pagenumber = 1; pagenumber <= n1; pagenumber++)
{
if (pdfReader.NumberOfPages >= pagenumber)
{
verticalPosition = verticalPosition - pdfReader.GetPageSize(pagenumber).Height;
cb.AddTemplate(writer.GetImportedPage(pdfReader, pagenumber), 0, verticalPosition);
}
else
{
break;
}
}
newPdf.Close();
How can the original file be copied into the target where both files would keep the same size if someone sends it to a printer?
Yes there is some redundancy in this code as I have been troubleshooting this for a little while now.
The key question here is a setting that would maintain the 8.25 x 814in and still allow adobe to open the file.
Thanks,
Mike
Thank you David.
After looking through Mr Lowagie's document and brief note about addTemplate.
cb.addTemplate(page, scale, 0, 0, scale, 0, 0)
The code was updated to utilize the new userunit and scaling.
Opening ok in Adobe now and reporting page length as expected
Once again the code is a little ugly still
RandomAccessFileOrArray ra = new RandomAccessFileOrArray(fn);
SizeF pageSize = GetPageSize(fn);
PdfReader pdfReader = new PdfReader(fn);
float USERUnitNewValue = ComputeUserUnit(pageSize);
int n1 = pdfReader.NumberOfPages;
if (pageSize.Height > 14400f) //14400 value is 72 pixels per inch over 200 inches. 200 inches seems to be adobe limit to a page
{ //determine the userunit to be used
USERUnitNewValue = pageSize.Height / 14400f;
}
float NewPageWidth = (pageSize.Width <= 14400f) ? pageSize.Width / USERUnitNewValue : pageSize.Width / USERUnitNewValue;
float NewPageHeight = pageSize.Height / USERUnitNewValue;
FileInfo file1 = new FileInfo(newfn);
DirectoryInfo directory1 = file1.Directory;
if (!directory1.Exists)
directory1.Create();
iTextSharp.text.Rectangle newPagesize = new iTextSharp.text.Rectangle(NewPageWidth, NewPageHeight);
Document newPdf = new Document(newPagesize);
PdfWriter writer = PdfWriter.GetInstance(newPdf, new FileStream(newfn, FileMode.Create));
writer.PdfVersion = PdfWriter.VERSION_1_6;
if (pageSize.Height > 14400)
{
writer.Userunit = USERUnitNewValue;
}
newPdf.SetMargins(0f, 0f, 0f, 0f);
newPdf.Open();
PdfContentByte cb = writer.DirectContent;
float verticalPosition = NewPageHeight;
for (int pagenumber = 1; pagenumber <= n1; pagenumber++)
{
if (pdfReader.NumberOfPages >= pagenumber)
{
/*convoluted page position. First position should be 0,0
unlike other counters this starts as page 1 so we need to subtract the
first page height away so that we start at the bottom of the previous image
* hmm seems that ths AddTemplate feature adds the pages in reverse order or
* at least the coordinate system sets 0,0 at the bottom left of the page
*/
float widthfactor = 1 / USERUnitNewValue; //Page scaling (width)
float heightfactor = 1 / USERUnitNewValue; //Page scaling (height)
//vertical position needs to take into account the new page height taking new UserUnit in affect
verticalPosition = verticalPosition - (pdfReader.GetPageSize(pagenumber).Height / USERUnitNewValue);
cb.AddTemplate(writer.GetImportedPage(pdfReader, pagenumber), heightfactor, 0, 0, widthfactor, 0, verticalPosition);
}
else
{
break;
}
}
newPdf.Close();
Thank you again for your help,
Mike

ItextSharp add image on center of page with the text under it

I'm trying add picture on centre(middle) of page PDF file with text, but I can't do it right. I use for image SetAbsolutePosition, but text don't stand under picture.
I need in my Pdf file next format of page:
I use next code:
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
ITextEvents ev = new ITextEvents();
writer.PageEvent = ev;
doc.Open();
var paragraph = new Paragraph();
var paragraph1 = new Paragraph();
var chunk = new Chunk("Text under picture", f14nb);
var chunk1 = new Chunk("Code of picture", f14);
img = ScaleImg(Image.GetInstance(imgNane_2));
img.SetAbsolutePosition((PageSize.A4.Width - img.ScaledWidth) / 2,
((PageSize.A4.Height - img.ScaledHeight) / 2));
paragraph.Add(img);
paragraph1.Add(chunk);
paragraph1.Add(chunk1);
doc.Add(paragraph);
doc.Add(paragraph1);
doc.Close();
private Image ScaleImg(Image img)
{
if (img.Height > img.Width)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 640 / img.Height;
img.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 500 / img.Width;
img.ScalePercent(percentage * 100);
}
return img;
}
I think, that I should use another way for solve my problem, but I don't know which.
Thank you.
I understood how do it.
This is for image with text:
public Image getWatermarkedImage(Document Doc, Image img, String watermarkText)
{
float width = img.ScaledWidth;
float height = img.ScaledHeight;
PdfTemplate template = cb.CreateTemplate(width, height);
template.AddImage(img, width, 0, 0, height, 0, 0);
ColumnText.ShowTextAligned(template, Element.ALIGN_RIGHT,
new Phrase(watermarkText, fontBold_14), width - 10, 10, 0);
return Image.GetInstance(template);
}
This is for adding text under image(main code):
var codeOfPicture = "*Code of picture* - *Код картинки*";
var chunk = new Chunk("Text under picture", font_14);
img = ScaleImg(Image.GetInstance(imgNane_1));//imgNane_2));
var tmpImg = getWatermarkedImage(doc, img, codeOfPicture);
var textY = ((PageSize.A4.Height - img.ScaledHeight) / 2) - 15;
var textX = PageSize.A4.Width / 2;
tmpImg.SetAbsolutePosition((PageSize.A4.Width - img.ScaledWidth) / 2,
((PageSize.A4.Height - img.ScaledHeight) / 2));
doc.Add(tmpImg);
ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase(chunk), textX, textY, 0);

center image in pdf using itextsharp

What I'm trying to do here is to add an image to a blank pdf. So far I've done it, but I want the image to be centered. How can I do this?
Here is my C# code:
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(System.IO.Path.Combine(filepath, strFilename), FileMode.Create));
doc.AddTitle("Document Title");
doc.Open();
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(#"C:\Users\Desktop\Winniethepooh.png");
image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
if (image1.Height > image1.Width)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 700 / image1.Height;
image1.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 540 / image1.Width;
image1.ScalePercent(percentage * 100);
}
//image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
doc.Add(image1);
doc.Close();
}
And this is the output:
https://drive.google.com/open?id=0BzaejXGgqBOAMzd0UlY2QWFXNms
What I want is that the image is centered on the page. Currently the image is on the top of the page.
I even set the image alignment, but why doesn't it center the image on the page?
You need to use SetAbsolutePosition() in order to center the image.
Just add the following to your code before you call doc.Add(image1);:
...
...
image1.SetAbsolutePosition((PageSize.A4.Width - image1.ScaledWidth) / 2, (PageSize.A4.Height - image1.ScaledHeight) / 2);
doc.Add(image1);
...
...
Hope this helps.

How to know if text exceeds the fill box in itextSharp

I am using the following code:
PdfReader PDFReader = new PdfReader("c:\\file.pdf");
FileStream Stream = new FileStream("c:\\new.pdf", FileMode.Create, FileAccess.Write);
PdfStamper PDFStamper = new PdfStamper(PDFReader, Stream);
for (int iCount = 0; iCount < PDFStamper.Reader.NumberOfPages; iCount++)
{
iTextSharp.text.Rectangle PageSize = PDFReader.GetCropBox(iCount + 1);
PdfContentByte PDFData = PDFStamper.GetOverContent(iCount + 1);
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
PDFData.BeginText();
PDFData.SetColorFill(CMYKColor.RED);
PDFData.SetFontAndSize(baseFont, 20);
PDFData.ShowTextAligned(PdfContentByte.ALIGN, SAMPLE DOCUMENT", (PageSize.Right + PageSize.Left) / 2, (PageSize.Top + PageSize.Bottom) / 2, 45);
PDFData.EndText();
}
PDFStamper.Close();
PDFReader.Close();
But sometimes the overlaid text exceeds the page size because I have hard coded the font as 20. So, is there any way to know if the overlaid text will exceed the page size? Because I want to use code like I will then use:
if(pagesize exceeds)
reduce font size by 1 point and check again .....
If the above doesn't work, then my next step is to use a PNG image that has the overlaid text in it and its background as transparent. then resize the image according to the pagesize and then overlay it.
however, I will prefer the first part. if not, then I will go for the second option.
After doing some minor calculations, this method should calculate the maximum font size to use for such a vertical text and apply it:
void Stamp(PdfContentByte cb, Rectangle rect, BaseFont bf, string text)
{
int altitude = Math.Max(bf.GetAscent(text), bf.GetDescent(text));
int width = bf.GetWidth(text);
double horizontalFit = Math.Sqrt(2.0) * 1000 * (rect.Left + rect.Right) / (width + 2 * altitude);
double verticalFit = Math.Sqrt(2.0) * 1000 * (rect.Bottom + rect.Top) / (width + 2 * altitude);
double fit = Math.Min(horizontalFit, verticalFit);
cb.BeginText();
cb.SetColorFill(CMYKColor.RED);
cb.SetFontAndSize(bf, (float) fit);
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text, (rect.Right + rect.Left) / 2, (rect.Top + rect.Bottom) / 2, 45);
cb.EndText();
}
You can call it like this:
using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create, FileAccess.Write)))
{
for (int iCount = 0; iCount < reader.NumberOfPages; iCount++)
{
Rectangle PageSize = reader.GetCropBox(iCount + 1);
PdfContentByte PDFData = stamper.GetOverContent(iCount + 1);
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
Stamp(PDFData, PageSize, baseFont, "SAMPLE DOCUMENT");
}
}
(By the way, I used your BaseFont but you should be aware that iText(Sharp) will ignore BaseFont.EMBEDDED for standard 14 fonts like BaseFont.HELVETICA.)
The result looks like this:
PS: If you (as expressed in your question) really don't want to use a font size above 20, you have to Min the fit value again with 20.

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.

Categories