itextsharp images are not coming next to one another - c#

I have 2 asp.net chart control which i want to convert to pdf. I am using iTextSharp to convert the images to pdf.
The issue is with the position of images, i want images to come next to other.
i tried to setpagesize but it didnt worked.
Document pdfDoc = new Document(PageSize.A4);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
Chart1.SaveImage(stream, ChartImageFormat.Png);
iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
chartImage.ScalePercent(75f);
pdfDoc.Add(chartImage);
Chart2.SaveImage(stream, ChartImageFormat.Png);
iTextSharp.text.Image chartImage1 = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
chartImage1.ScalePercent(75f);
pdfDoc.Add(chartImage1);

The best way to position images next to each other, is to add them to a ´PdfPTable´. I've created a small example in Java: ImagesNextToEachOther
As you can see, we wrap images inside a cell, asking the cell to scale the image so that it fits the width of the cell.
You'll have to make small changes to the code, as I've used iText instead of iTextSharp, but the difference should be minimal.

Related

Continuous Labelling using iTextSharp PDF

I have working iTextsharp code for printing labels. Now the problem is, I have a requirement to print the labels in Continuous paper which i am not able to select in iTextsharp configuration (iTextSharp.text.PageSize.A4). Please advice how can i select the page size according to my current scenario.
Thanks
Your problem is related to PDF as a document format. In PDF, the content is distributed over different pages. You can define the size of such a page yourself. You mention iTextSharp.text.PageSize.A4, but you can define the page size as a Rectangle object yourself. See iTextsharp landscape document
If you want a long, narrow page, you could define the page size like this:
Document Doc = new Document(new Rectangle(595f, 14400f));
There are some implementation limits though. The maximum height or width of a page is 14,400 user units. See the blog post Help, I only see blank pages in my PDF!
However, I am pretty sure that you don't want to create a long narrow page. If you want to print labels on "continuous paper", you want to create a PDF document in which every page has the size of exactly one label. Your PDF will have as many pages as there are labels.
Suppose that the size of one label is 5 by 2 inch (width: 12.7cm; height: 5.08cm), then you should create a document like this:
Document Doc = new Document(new Rectangle(360, 144));
And you should make sure that all the content of a label fits on a single page. Your label printer should know that each page in the PDF should be printed on a separate label.
(Thank you #amedeeVanGasse for correcting my initial answer.)

iText7, Is there a way to control carriage return inside rectangle?

I'm using iText 7 with C# and I have to write a long line.
With canvas.BeginText().ShowText("My text") I can't find a way to make the text pass on a second line, \n is not recognized.
So I used rectangles and document renderer but I have the same problem, I can't control where I want my text to create a new line.
I use an existing PDF (a model) where I have to write some texts (as short as a single line) and some paragraphs (composed of several lines). Those elements are defined in an xml where I can have some carriage returns to delimit new lines in paragraphs. Is short, the document is composed dynamically and it's content and element's placement are defined inside an xml file.
Adding content with low-level methods such as BeginText(), ShowText(), EndText() and so on, requires a sound knowledge of the PDF specification (ISO 32000). The fact that you are surprised at the fact that \n is ignored tells me that you aren't that well versed in PDF.
iText was written for people who don't want to deal with the low-level syntax of PDF. For instance: if you want to add text inside a rectangle with iText, you just have to create a Canvas object to which you pass a Rectangle object:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfPage page = pdf.AddNewPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle rectangle = new Rectangle(36, 650, 100, 100);
Canvas canvas = new Canvas(pdfCanvas, pdf, rectangle);
PdfFont font = PdfFontFactory.CreateFont(FontConstants.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.CreateFont(FontConstants.TIMES_BOLD);
Text title =
new Text("The Strange Case of Dr. Jekyll and Mr. Hyde").SetFont(bold);
Text author = new Text("Robert Louis Stevenson").SetFont(font);
Paragraph p = new Paragraph().Add(title).Add(" by ").Add(author);
canvas.Add(p);
pdf.Close();
This example can be found in chapter 2 of the online iText 7 tutorial.
The screenshot shows how a long sentence was added inside a Rectangle, and how that sentence got distributed over different lines (introducing new lines automatically). The concept of the \n character doesn't exist in PDF (check ISO 32000 when in doubt). If you want to introduce a newline, it's sufficient to put one part of the content in one Paragraph and the other part in another Paragraph.

iTextSharp fill form with non embedded font (override font setting from Acrobat)

I'm trying to fill a PDF form using iTextSharp, but being cursed with the need for Scandinavian characters (åäöøæ etc) I can't use the built in Helvetica. The closest thing would be to use Arial, BUT if I embed Arial I'm stuck with a PDF template 6 times larger than the original file.
So, my question, is there a way to use Helvetica when creating the template (in order to keep the size down) and then override this in the code when filling the PDF?
As it stands right now I have this:
PdfStamper pdfStamper = new PdfStamper(new PdfReader(templateFile), new FileStream(fileName, FileMode.Create));
AcroFields acroFields = pdfStamper.AcroFields;
acroFields.SetField("txtDocumentId", dnData.DocumentId);
acroFields.SetField("txtName", dnData.Name);
pdfStamper.FormFlattening = true;
pdfStamper.Close();
I would prefer to define an unembedded font (Arial) for the fields since all end users will have Arial installed on their Machines.
Is this doable?

PDF stamping is not working in pages where does not have header info or body

Using the below code pdf stamping is working fine but if the pdf page does not have header info or body is empty then stamping is not working I mean pdfData.ShowText(strCustomMessage) is not working.
//create pdfreader object to read sorce pdf
PdfReader pdfReader=new PdfReader(Server.MapPath("Input") + "/" + "input.pdf");
//create stream of filestream or memorystream etc. to create output file
FileStream stream = new FileStream(Server.MapPath("Output") + "/output.pdf", FileMode.OpenOrCreate);
//create pdfstamper object which is used to add addtional content to source pdf file
PdfStamper pdfStamper = new PdfStamper(pdfReader,stream);
//iterate through all pages in source pdf
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
//Rectangle class in iText represent geomatric representation... in this case, rectanle object would contain page geomatry
Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
//pdfcontentbyte object contains graphics and text content of page returned by pdfstamper
PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);
//create fontsize for watermark
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40);
//create new graphics state and assign opacity
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.4F;
//set graphics state to pdfcontentbyte
pdfData.SetGState(graphicsState);
//set color of watermark
pdfData.SetColorFill(BaseColor.BLUE);
//indicates start of writing of text
pdfData.BeginText();
//show text as per position and rotation
pdfData.SetTextMatrix(pageRectangle.Width/2,pageRectangle.Height/2); pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9);
string strCustomMessage="PDF Stamping Test"
pdfData.ShowText(strCustomMessage);
//call endText to invalid font set
pdfData.EndText();
}
//close stamper and output filestream
pdfStamper.Close();
stream.Close();
I think your question is wrong. Would do you mean when you say "the pdf page does not have header info or body is empty"? Because that doesn't make sense.
A few observations: I think you're using an obsolete version of iTextSharp. Read the FAQ to find out why this is a bad idea.
Newer versions of iTextSharp will throw an exception because of this error:
pdfData.BeginText();
//show text as per position and rotation
string strCustomMessage="PDF Stamping Test"
pdfData.ShowText(strCustomMessage);
//call endText to invalid font set
pdfData.EndText();
In these lines, you are violating the PDF reference: you are showing text within a BT/ET sequence without defining a font and size. Had you used a newer version of iTextSharp, an exception would have pointed that out. You need to move the line with the SetFontAndSize() method inside the BeginText()/EndText() sequence. It's illegal to use it outside a text object.
Also: why are you using BeginText()/EndText() to add text? That is code for PDF specialists. Read the documentation to find out how to use ColumnText.ShowTextAligned(). The ShowTextAligned() method is a convenience method written for developer who aren't fluent in PDF syntax.
Whether or not the text added with ShowText() is visible will depend on:
the opacity of the page: Suppose that your page consists of a scanned image, you won't see any text, because you're adding the text under the image. Use the GetOverContent() method instead of the GetUnderContent() method to avoid this.
the position on the page: I see that you get the size of the page using the GetPageSizeWithRotation() method, but I don't see you doing anything with that info. I don't see at which coordinate you are showing the text. That is also wrong. You need to make sure that you add the text inside the visible area of the page.
This answer lists several problems with your code. It would be better if you simplify your code by using the ShowTextAligned() and correct X,Y coordinates.

Using iTextSharp PdfStamper to overlay an image on existing PDF

I am able to overlay an image onto an existing PDF document using the PDFStamper and the PdfContentByte content.AddImage method.
My problem comes up when the existing document already has an image overlayed on top. You can actually see the top edge of the small image I am trying to overlay. It is clearly hidden beneath the existing image overlay.
I am having issues trying to get my overlayed image to show up on top of the existing image overlay.
My code:
System.Drawing.Image bitmap
PdfReader pdfReader = new PdfReader(pathToOriginalPdf);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(pathToTimestampedPdf, FileMode.Create, FileAccess.Write, FileShare.None));
MemoryStream imageStream = new MemoryStream();
bitmap.Save(imageStream, ImageFormat.Bmp);
byte[] bitmapBytes = imageStream.ToArray();
iTextSharp.text.Image image = Image.GetInstance(bitmapBytes);
PdfContentByte underContent;
try
{
underContent = pdfStamper.GetOverContent(1);
underContent.AddImage(image);
}
I need a way to either flatten the existing image overlay onto the PDF content or set the z-order such that my newly added overlay can sit on top.
For some reason the PdfStamper is choosing to place the new image below the existing one.
Thanks in advance.
It would help if we could see the PDF in question. Then we wouldn't have to guess, we would know.
None the less, I suspect your "existing image overlay" is part of an annotation. Nothing you put into page contents will ever appear above an annotation.
Options (if I'm right):
Add your own annotation
For this, I'd use a PushbuttonField with LAYOUT_ICON_ONLY. Draw your image into a PdfTemplate, and use that for the button's "icon".
Z-order for annotations is determined by the order of the page's annotation array. New annotations are appended to this array. No problem.
PushbuttonField fld = new PushbuttonField(stamper.getWriter(), box, name);
fld.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
fld.setImage(myImage);
stamper.addAnnotation(fld.getField(), 1);
You might need to mess around with setScaleIcon(), setHorizontalAdjustment(), setVerticalAdjustment(), setProportionalIcon(), and maybe a couple others to get your image to look exactly how you want it.
Flatten in one pass, add your image in another
If the existing image annotation is something iText can flatten (maybe, maybe not), you can do what you want in two passes. The first pass would simply "setFormFlattening(true);close();", while the second would be everything you're doing now.
ByteArrayOutputStream output = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper( firstReader, output );
stamper.setFormFlattening(true);
stamper.setFreeTextFlatten(true); // probably not needed.
stamper.close();
PdfReader secondReader = new PdfReader(output.toByteArray());
FileOutputStream finalOutput = new FileOutputStream( outputPath );
stamper = new PdfStamper(secondReader, finalOutput);
// do your thing here.
stamper.getOverContent(1).addImage(image);

Categories

Resources