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).
Related
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();
I'm trying to enlarge the icon of a PDF sticky note. Here's an image showing the sticky icon that I've stamped on the first page of the PDF for context:
I was under the impression the icon was guided by a rectangle that could be manipulated. Here's my code that has not been effective yet:
using (PdfStamper stamp = new PdfStamper(reader, fs))
{
PdfWriter attachment = stamp.Writer;
foreach (string file in files_to_attach)
{
PdfFileSpecification pdfAttch = PdfFileSpecification.FileEmbedded(attachment, file, file, null);
stamp.AddFileAttachment(file, pdfAttch);
}
//Create Note for first page
Rectangle rect = new Rectangle(850, 850, 650, 650);
PdfAnnotation annotation = PdfAnnotation.CreateText(stamp.Writer, rect, "TITLE OF NOTE", "Body text of the note", false, "Comment");
//Enlarge the Sticky Note icon
PdfDictionary page = reader.GetPageN(1);
PdfArray annots = page.GetAsArray(PdfName.ANNOTS);
PdfDictionary sticky = annots.GetAsDict(0);
PdfArray stickyRect = sticky.GetAsArray(PdfName.RECT);
PdfRectangle stickyRectangle = new PdfRectangle(
stickyRect.GetAsNumber(0).FloatValue - 50, stickyRect.GetAsNumber(1).FloatValue - 20,
stickyRect.GetAsNumber(2).FloatValue, stickyRect.GetAsNumber(3).FloatValue - 30);
sticky.Put(PdfName.RECT, stickyRectangle);
//Apply the Note to the first page
stamp.AddAnnotation(annotation, 1);
stamp.Close();
}
I thought I could change the float values and that would change the shape of the icon but so far it has not effected it all. Thank you for any suggestions.
You can't. The icon that is displayed for the "Comment" annotation is supplied by the viewer. The rect property is only used to define the lower left corner of where the icon gets placed on the page by the viewer. According to the PDF specification for annotations with the type "Text", "Conforming readers shall provide predefined icon appearances for at least the following standard names: Comment, Key, Note, Help, NewParagraph, Paragraph, Insert.
You can, however, create your own image, of any size, and use it as the appearance for a "Stamp" annotation. It can even look exactly like a "Comment" icon, just bigger. It would end up functioning in the same way for the end user.
I had a fillable PDF document (2 pages in total) consisting of different sizes of page; the first page is 8.5 * 11 inches (612 * 792), containing fillable fields; the second page is 9.5 * 12 inches (684 * 864), containing No fillable fields. Even though the second page is larger, the margin of it can be ignored. In other word, if get the second page printed as A4, no content would be cut.
However, when I am doing the document concatenation(using 612 *792), all second pages will be lined up at the left bottom corner of the page, making partial contents lost on top and right margin of the page. Even though full content can be fit in when (684 *864) is applied, all first pages are lined up at the left bottom corner of the page as well, making it a wide blank margins on top and right of page.
Is there anyway that I can get pages be written in center of page all the times so that I can use size of 612* 792 without losing contents in second pages?
Below is the concatenation method:
private static byte[] ConcatContents(List<byte[]> pdf)
{
byte[] all;
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document(new Rectangle(612, 792));
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
PdfReader reader;
foreach (byte[] p in pdf)
{
reader = new PdfReader(p);
int pages = reader.NumberOfPages;
// loop over document pages
for (int i = 1; i <= pages; i++)
{
doc.NewPage();
page = writer.GetImportedPage(reader, i);
cb.AddTemplate(page, 0, 0);
}
}
doc.Close();
all = ms.ToArray();
ms.Flush();
ms.Dispose();
}
return all;
}
[UPDATE]
Original Page Size difference in PDF
After Page concatenation, some of the content lost because it seems like PDF was generated from left bottom corner up. The page size difference causes the lost of page content. As you can see in the picture below, the first line of second page content
"BECUASE THIS FORM IS USED BY VARIOUS GOVERNMENT..."
was cut off, as well as some content in the right.
Well, Thanks to plinth's suggestions, I found out that the below code work perfectly to adjust all the second pages to center of the page. Although it doesn't look like a good practice, it works eventually.
// loop over document pages
for (int i = 1; i <= pages; i++)
{
doc.NewPage();
page = writer.GetImportedPage(reader, i);
if (i == 1)
{
cb.AddTemplate(page, 0, 0);
}
else
{
float page1Height, page1Width, page2Height, page2Width;
page1Height = reader.GetPageSizeWithRotation(i - 1).Height;
page1Width = reader.GetPageSizeWithRotation(i - 1).Width;
page2Height = reader.GetPageSizeWithRotation(i).Height;
page2Width = reader.GetPageSizeWithRotation(i).Width;
cb.AddTemplate(page, (page1Width - page2Width) / 2, (page1Height - page2Height) / 2);
}
}
Here is the displayed result
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.
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 ();
}
}