center image in pdf using itextsharp - c#

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.

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

iTextSharp Image minimum Table cell height

I am trying to append images to a PDF document, but the image width must = doc.PageSize.Width and height in ratio with the image width.
I am appending individual images, each in its own table and in a cell using the following method
public void AddImage(Document doc, iTextSharp.text.Image Image)
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
table.TotalWidth = doc.PageSize.Width;
PdfPCell c = new PdfPCell(Image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.FixedHeight = (doc.PageSize.Width / Image.Width) * Image.Height;
c.MinimumHeight = (doc.PageSize.Width / Image.Width) * Image.Height;
table.AddCell(c);
doc.Add(table);
}
The Document code part (Do not think this is necessary though):
using (PDFBuilder pdf = new PDFBuilder())
{
using (var doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
var image = iTextSharp.text.Image.GetInstance(Request.MapPath("~/Images/Nemo.jpg"));
pdf.AddImage(doc, image);
pdf.AddImage(doc, image);
pdf.AddImage(doc, image);
}
}
What I want is for the images to be 100% width, and if not, the image must append on the next page.
This is currently what I am getting
And this is what I want
Any help would be greatly appreciated, thank you in advance!
Got It!
This line needed to be added:
c.Image.ScaleToFitHeight = false;
My Method
public void AddImage(Document doc, iTextSharp.text.Image Image)
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
PdfPCell c = new PdfPCell(Image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.Image.ScaleToFitHeight = false; /*The new line*/
table.AddCell(c);
doc.Add(table);
}

Overlay image onto PDF using PDFSharp

Can't seem to find much out there for this. I've a PDF, onto which I'd like to overlay an image of an electronic signature. Any suggestions on how to accomplish that using PDFSharp?
Thanks
Try the following
private void GeneratePDF(string filename, string imageLoc)
{
PdfDocument document = new PdfDocument();
// Create an empty page or load existing
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
DrawImage(gfx, imageLoc, 50, 50, 250, 250);
// Save and start View
document.Save(filename);
Process.Start(filename);
}
void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
XImage image = XImage.FromFile(jpegSamplePath);
gfx.DrawImage(image, x, y, width, height);
}
This will generate a new PDF with the specified image near the top of the page. If you need to use an existing document change the PdfDocument constructor to
PdfDocument document = new PdfDocument(filename);
where filename is the name of the file to load and change the PdfPage line to
PdfPage page = document.Pages[pageNum];
where pageNum is the number of the page on which you need to add the image.
After that, it just a matter of getting the positioning on the page by altering the parameters for DrawImage to suit.
DrawImage(gfx, imageLoc, 50, 50, 250, 250);
Good luck!
This will help you:
PdfDocument document = pdf;
// Create a new page
PdfPage page = document.Pages[0];
page.Orientation = PageOrientation.Portrait;
XGraphics gfx = XGraphics.FromPdfPage(page, XPageDirection.Downwards);
// Draw background
gfx.DrawImage(XImage.FromFile("pdf_overlay.png"), 0, 0);
Just add the path to the image you want, and specify the position of the image.
To roughly maintain the aspect ratio, I used #Kami's answer and "roughly" centered it.
The assumption made is that the pdf width is 600 and pdf height is 800, we will make use of the middle 500 and 700 of the page only, leaving the 4 sides have at least 50 in length as margin.
public static void GeneratePdf(string outputPath, string inputPath)
{
PdfSharp.Pdf.PdfDocument document = new PdfSharp.Pdf.PdfDocument();
// Create an empty page or load existing
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
DrawImage(gfx, inputPath);
// Save and start View
document.Save(outputPath);
Process.Start(outputPath);
}
public static void DrawImage(XGraphics gfx, string imagePath)
{
XImage image = XImage.FromFile(imagePath);
var imageHeight = image.PixelHeight;
var imageWidth = image.PixelWidth;
int height;
int width;
int x;
int y;
width = 500;
height = (int) Math.Ceiling((double) width * imageHeight / imageWidth);
x = 50;
y = (int) Math.Ceiling((800 - height) / 2.0);
if(height > 700)
{
height = 700;
width = (int) Math.Ceiling(imageWidth * (double) height / imageHeight);
y = 50;
x = (int) Math.Ceiling((600 - width) / 2.0);
}
gfx.DrawImage(image, x, y, width, height);
}

create PDF file using itextsharp in 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

Categories