Adding different sized pages to PDF using iTextSharp - c#

I have a table and a chart to be added to a PDF Document. I have used the iTextSharpLibrary to add the contents to the PDF file.
Actually the problem is that the chart has a width of 1500px and the table fits in comfortably in an A4 page size.
Actually the chart image that I get must not be scaled to fit in the page as it reduces the viewability. Hence, I need to add a new page that has a wider width than the other ones or at least change the page orientation to landscape and then add the image. How do I do this?
This is the code that I used to add a new page and then resize the page and then add the image. This is not working. Any fixes?
var imageBytes = ImageGenerator.GetimageBytes(ImageSourceId);
var myImage = iTextSharp.text.Image.GetInstance(imageBytes);
document.NewPage();
document.SetPageSize(new Rectangle(myImage.Width, myImage.Height));
myImage.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
document.Add(myImage);

I fixed the Issue. I have to set the page size before calling the GetInstance of the Pdfdocument. Then, i can give different pagesizes for each page

I'm not sure what you mean by before calling the GetInstance of the Pdfdocument, but setting the pageSize right before calling newPage works.
Here follows the c# code to create a new pdf that's made of two pictures, no matter how wild their sizes difference is. The important lines here are the new Document and SetPageSize ones.
static public void MakePdfFrom2Pictures (String pic1InPath, String pic2InPath, String pdfOutPath)
{
using (FileStream pic1In = new FileStream (pic1InPath, FileMode.Open))
using (FileStream pic2In = new FileStream (pic2InPath, FileMode.Open))
using (FileStream pdfOut = new FileStream (pdfOutPath, FileMode.Create))
{
//Load first picture
Image image1 = Image.GetInstance (pic1In);
//I set the position in the image, not during the AddImage call
image1.SetAbsolutePosition (0, 0);
//Load second picture
Image image2 = Image.GetInstance (pic2In);
// ...
image2.SetAbsolutePosition (0, 0);
//Create a document whose first page has image1's size.
//Image IS a Rectangle, no need for new Rectangle (Image.Width, Image.Height).
Document document = new Document (image1);
//Assign writer
PdfWriter writer = PdfWriter.GetInstance (document, pdfOut);
//Allow writing
document.Open ();
//Get writing head
PdfContentByte pdfcb = writer.DirectContent;
//Put the first image on the first page
pdfcb.AddImage (image1);
//The new page will have image2's size
document.SetPageSize (image2);
//Add the new second page, and start writing in it
document.NewPage ();
//Put the second image on the second page
pdfcb.AddImage (image2);
//Finish the writing
document.Close ();
}
}

Related

How can I add a text behind an image in IText7 c#?

I am generating a pdf from others with IText7 in C# and I need to add information in a corner of each page automatically, I add the information but in some pages, the content occupies the entire page and I need the information to be left behind in those cases of the content, I attach the image of the result, thanks in advance
I am using a canvas and Div to add the text
PdfPage pag = pdfDocument.GetLastPage();
Canvas canvas = new Canvas(pag, pag.GetPageSize());
var div = new Div().SetMargin(0).SetPadding(0).SetKeepTogether(true);
div.SetFixedPosition(0, 0, pag.GetPageSize().GetWidth());
div.Add(new Paragraph("info").SetFontSize(12));
canvas.Add(div);
canvas.Close();
Sorry my English
result:
Pdf text added result
expected:
Pdf text added Expected
I have found the solution, I create a PDFCanvas and indicate that NewContentStreamBefore(), and it already adds the information behind the page
PdfPage pag = pdfDocument.GetLastPage();
PdfCanvas under = new PdfCanvas(pag.NewContentStreamBefore(), pag.GetResources(), pdfDocument);
Canvas canvas = new Canvas(under, pag.GetPageSize());
var div = new Div().SetMargin(0).SetPadding(0).SetKeepTogether(true);
div.SetFixedPosition(0, 0, pag.GetPageSize().GetWidth());
div.Add(new Paragraph("info").SetFontSize(12));
canvas.Add(div);
canvas.Close();

Create PDFdocument whith various pages format(iTextSharp) [duplicate]

I want to create a pdf file using itext that has unequal page sizes.
I have these two rectangles:
Rectangle one=new Rectangle(70,140);
Rectangle two=new Rectangle(700,400);
and i am writing to the pdf like this :
Document document = new Document();
PdfWriter writer= PdfWriter.getInstance(document, new FileOutputStream(("MYpdf.pdf")));
when I create the document, I have the option to specify the page size , but I want different page sizes for different pages in my pdf.
Is it possible to do that ?
Eg. The first page will have rectangle one as the page size, and the second page will have rectangle two as the page size.
I've created an UnequalPages example for you that shows how it works:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
Rectangle one = new Rectangle(70,140);
Rectangle two = new Rectangle(700,400);
document.setPageSize(one);
document.setMargins(2, 2, 2, 2);
document.open();
Paragraph p = new Paragraph("Hi");
document.add(p);
document.setPageSize(two);
document.setMargins(20, 20, 20, 20);
document.newPage();
document.add(p);
document.close();
It is important to change the page size (and margins) before the page is initialized. The first page is initialized when you open() the document, all following pages are initialized when a newPage() occurs. A new page can be triggered explicitly (using the newPage() method in your code) or implicitly (by iText, when a page was full and a new page is needed).

Setting image position using iTextSharp

I have a problem with regards on the page orientation of the paper size.
I have a pdf file which contains portrait and landscape page.
this code works perfectly.
string FileLocation = "c:\\Temp\\SomeFile.pdf";
string WatermarkLocation = "c:\\Temp\\watermark.gif";
Document document = new Document();
PdfReader pdfReader = new PdfReader(FileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf","[temp][file].pdf"), FileMode.Create));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
img.SetAbsolutePosition(250,300); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)
PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
waterMark = stamp.GetUnderContent(page);
waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();
// now delete the original file and rename the temp file to the original file
File.Delete(FileLocation);
File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation);
since I'm using absolute value to set the image position.
img.SetAbsolutePosition(250,300);
How can T set the image position if the page is landscape or portrait?
note: One pdf with landscape and portrait page orientation.
Is there by chance that I can use if statement?
if (//paper is landscape)
{
//code here
}
else
{
//code here
}
What do you want to achieve?
Normally, iText takes into account the value of the page rotation. This means that when a page is rotated, the coordinates will be rotated too.
If you want to overrule this, you can add this line:
stamper.RotateContents = false;
This is explained in Chapter 6 of my book. You can try this example to see the difference:
No rotation, text added normally: hello1.pdf
Rotation, text added normally ( = rotated): hello2.pdf
Rotation, text added with rotation ignored: hello3.pdf
Of course, this assumes that a rotation was defined for the pages. Sometimes, landscape is mimicked by defining a different page size instead of defining a rotation.
In that case, you should also read Chapter 6 because it explains how to get the MediaBox of a document. see the example PageInformation that introduces methods such as GetPageSize(), GetRotation() and GetPageSizeWithRotation().
This is all documented, but if it doesn't answer your question, please clarify. As demonstrated in the example, the rotation is taken into account by default when adding new content, so maybe I misunderstood the question.

Resize Image of any size to fixed dimension using C# ASP.Net web form

I have done image resizing while allowing user to upload a specific size image and then crop them to different dimension i have also used jCrop in project to allow users to upload a image of specific size and then select the image area & crop it accordingly.
In new project i have a requirement where user can upload any size image which is at least larger than 500Px in width and then i have to allow user to select the part of image using jCrop and then save image in different dimension of 475x313 , 310x205 while maintaining the aspect ration.
I can do it with if i allow the used to upload a fixed size image but i am not sure how i can handle variable size image.
I also need to display the image uploaded before cropping in a fixed size box.. let us say 300x200. in this area i have to allow the user to select the part of the image before i can crop.
Issue i am facing is how to handle variable length image and show it is a fixed image box of 300x200px.
I wrote an article on using jCrop with dynamically-resized uploaded images, which seems to be what you're needing.
If you're looking for an open-source ASP.NET control that does it for you, check out cropimage.net.
Want to going to by programmatically than you can try this :
if you are using file upload for upload images
string path = Path.GetFileName(fileuploaderID.PostedFile.FileName);
ConvertThumbnails(width, height, fileuploaderID.FileBytes, path);
your function
public void ConvertThumbnails(int width, int height, byte[] filestream, string path)
{
// create an image object, using the filename we just retrieved
var stream = new MemoryStream(filestream);
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
try
{
int fullSizeImgWidth = image.Width;
int fullSizeImgHeight = image.Height;
float imgWidth = 0.0F;
float imgHeight = 0.0F;
imgWidth = width;
imgHeight = height;
Bitmap thumbNailImg = new Bitmap(image, (int)imgWidth, (int)imgHeight);
MemoryStream ms = new MemoryStream();
// Save to memory using the Jpeg format
thumbNailImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
// read to end
byte[] bmpBytes = ms.GetBuffer();
item.Attachments.Add(path, bmpBytes);
thumbNailImg.Dispose();
ms.Close();
}
catch (Exception)
{
image.Dispose();
}
}

Novacode Docx Create Image from Bitmap

Background
My project is urgent and requires that I iterate a large XML file and return Base64 encoded images.
Each image must be inserted into an MS Word doc, and I am using the DocX library for that.
I am converting the Base64 strings to bitmap with no problem.
Problem
For the life of me, I can't seem to get the bitmaps into a Novacode.Image object which can then be inserted to the document. NOTE: I already know how to convert to System.Drawing.Image format. It is Novacode.Image format (DocX) that is giving me grief.
If I try to convert a la (Novacode.Image)somebitmap; I get Can not cast expression of type Image to Bitmap. If I try to initialize a new Novacode.Image object I get Can not access internal constructor Image here.
Using C#, .NET 4, Forms App, lots of coffee.
Question
Only Novacode.Image objects can be inserted into the MS Word doc via the library, so how the heck do I get my bitmap in there??
I am bleary-eyed at this point so perhaps I am just missing something simple.
You have to use the DocX.AddImage() method to create a Novacode.Image object.
Follow these 5 steps to add a image to a word document:
Save your picture into a memory stream.
Create the Novacode.Image object by calling AddImage() method.
Create a picture by calling CreatePicture() on the Novacode.Image object created in step 2.
Set the shape of the picture (if needed).
Insert your picture into a pragraph.
The sample below shows how to insert a image into a word document:
using (DocX doc = DocX.Create(#"Example.docx"))
{
using (MemoryStream ms = new MemoryStream())
{
System.Drawing.Image myImg = System.Drawing.Image.FromFile(#"test.jpg");
myImg.Save(ms, myImg.RawFormat); // Save your picture in a memory stream.
ms.Seek(0, SeekOrigin.Begin);
Novacode.Image img = doc.AddImage(ms); // Create image.
Paragraph p = doc.InsertParagraph("Hello", false);
Picture pic1 = img.CreatePicture(); // Create picture.
pic1.SetPictureShape(BasicShapes.cube); // Set picture shape (if needed)
p.InsertPicture(pic1, 0); // Insert picture into paragraph.
doc.Save();
}
}
Hope, this helps.
Thanks Hans and Martin, I was able to use this as a basis for ensuring large image files (photos) are always sized to fit on the page. The max width and max height can be changed depending on your page size.
using (MemoryStream ms = new MemoryStream())
{
System.Drawing.Image myImg = System.Drawing.Image.FromFile(imageDirectory + i.FileName);
double xScale = 1;
double yScale = 1;
double maxWidthInches = 6.1; // Max width to fit on a page
double maxHeightInches = 8.66; // Max height to fit on a page
// Normalise the Horizontal and Vertical scale for different resolutions
double hScale = ((double)96 / myImg.HorizontalResolution);
double vScale = ((double)96 / myImg.VerticalResolution);
// Scaling required to fit in x direction
double imageWidthInches = myImg.Width / myImg.HorizontalResolution; // in inches using DPI
if (imageWidthInches > maxWidthInches)
xScale = maxWidthInches / imageWidthInches * hScale;
// Scaling required to fit in y direction
double imageHeightInches = myImg.Height / myImg.VerticalResolution;
if (imageHeightInches > maxHeightInches)
yScale = maxHeightInches / imageHeightInches * vScale;
double finalScale = Math.Min(xScale, yScale); // Use the smallest of the two scales to ensure the picture will fit in both directions
myImg.Save(ms, myImg.RawFormat); // Save your picture in a memory stream.
ms.Seek(0, SeekOrigin.Begin);
Novacode.Image img = document.AddImage(ms); // Create image.
Paragraph p = document.InsertParagraph();
Picture pic = img.CreatePicture(); // Create picture.
//Apply final scale to height & width
double width = Math.Round((double)myImg.Width * finalScale);
double height = Math.Round((double)myImg.Height * finalScale);
pic.Width = (int)(width);
pic.Height = (int)(height);
p.InsertPicture(pic); // Insert picture into paragraph.
}
Thanks Hans. I had an Issue where the Image is inserted at the wrong size based on the DPI so I used this to scale the image based on DPI, 96 dpi seemed to be the basis of the scaled image in word:
using (MemoryStream ms = new MemoryStream())
{
System.Drawing.Image myImg = System.Drawing.Image.FromFile(path);
//Calculate Horizontal and Vertical scale
float Hscale = ((float)96 / myImg.HorizontalResolution);
float Vscale = ((float)96 / myImg.VerticalResolution );
myImg.Save(ms, myImg.RawFormat); // Save your picture in a memory stream.
ms.Seek(0, SeekOrigin.Begin);
Novacode.Image img = proposal.AddImage(ms); // Create image.
Picture pic1 = img.CreatePicture(); // Create picture.
//Apply scale to height & width
pic1.Height = (int)(myImg.Height * Hscale);
pic1.Width = (int)(myImg.Width * Vscale);
a.InsertPicture(pic1, 0); // Insert picture into paragraph.
}

Categories

Resources