If adding template to contentByte then the image that is added to document is not shown.
writer = PdfWriter.getInstance(document, fos);
cb = writer.getDirectContent();
document.newPage();
//*******************************************************
// *** adding following line causes the image not to be shown ***
cb.addTemplate(form, 0, 0);
//*******************************************************
cb.beginText();
cb.setRGBColorFill(0,0,0);
cb.setFontAndSize(bf, fontSize);
//*******************************************************
// *** the image is shown only if addTemplate is not called above.***
document.add(image);
//*******************************************************
cb.showTextAligned(...);
cb.endText();
Fixed the issue by calling writer.getDirectContentUnder(); instead of writer.getDirectContent();
Related
Only last slide is getting convert means last slide overlapping every slides. Can anyone suggest how to combine it in one PDF?
I have tried with different approach but they are first creating image and then PDF.
FileInputStream inputStream = new FileInputStream(in);
SlideShow ppt = new SlideShow(inputStream);
inputStream.close();
Dimension pgsize = ppt.getPageSize();
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(out));
document.setPageSize(new Rectangle(
(float)pgsize.getWidth(), (float)pgsize.getHeight()));
document.open();
PdfGraphics2D graphics= null;
for (int i = 0; i < ppt.getSlides().length; i++) {
Slide slide = ppt.getSlides()[i];
graphics = (PdfGraphics2D) pdfWriter.getDirectContent()
.createGraphics((float)pgsize.getWidth(), (float)pgsize.getHeight());
slide.draw(graphics);
}
graphics.dispose();
document.close();
I tiied to add a TextBox to the right corner of the existing pdf using c#, but im unable to get it done. I have wrote the following code,but it is not helping in solving the problem, can any body please suggest me
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
PdfReader.unethicalreading = true;
Paragraph p = new Paragraph();
Document doc = new Document();
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
PdfContentByte canvas = stamper.GetOverContent(1);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
//PdfContentByte cb = null;
//PdfImportedPage page;
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
var size1 = reader.GetPageSize(i);
w = size1.Width;
h = size1.Height;
stamper.FormFlattening = true;
TextField tf = new TextField(stamper.Writer, new iTextSharp.text.Rectangle(0, 0, 300, 100), displaytext);
//Change the orientation of the text
tf.Rotation = 0;
stamper.AddAnnotation(tf.GetTextField(), i);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(str, bytes);
As the OP clarified in comments to the question, he wants
to add the text as a page content in the right bottom corner of the page and
the page content previously existing there to be removed.
A simple implementation of this would include
first covering the existing page content with a filled rectangle and
then writing text there.
These tasks can be achieved with these helper methods:
void EmptyTextBoxSimple(PdfStamper stamper, int pageNumber, Rectangle boxArea, BaseColor fillColor)
{
PdfContentByte canvas = stamper.GetOverContent(pageNumber);
canvas.SaveState();
canvas.SetColorFill(fillColor);
canvas.Rectangle(boxArea.Left, boxArea.Bottom, boxArea.Width, boxArea.Height);
canvas.Fill();
canvas.RestoreState();
}
and
ColumnText GenerateTextBox(PdfStamper stamper, int pageNumber, Rectangle boxArea)
{
PdfContentByte canvas = stamper.GetOverContent(pageNumber);
ColumnText columnText = new ColumnText(canvas);
columnText.SetSimpleColumn(boxArea);
return columnText;
}
E.g. like this:
using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
Rectangle cropBox = reader.GetCropBox(1);
Rectangle bottomRight = new Rectangle(cropBox.GetRight(216), cropBox.Bottom, cropBox.Right, cropBox.GetBottom(146));
EmptyTextBoxSimple(stamper, 1, bottomRight, BaseColor.WHITE);
ColumnText columnText = GenerateTextBox(stamper, 1, bottomRight);
columnText.AddText(new Phrase("Some test text to draw into a text box in the lower right corner of the first page"));
columnText.Go();
}
For this source page
the sample code generates this
Addendum
In a comment the OP indicated
it is working for all files but for some pdf files it is displaying in the middle
Eventually he supplied a sample file for which the issue occurs. And indeed, with this file the issue could be reproduced.
The cause for the issue is that the pages in the sample file use page rotation, something that iText (only) partially allows users to ignore. In particular iText automatically rotates text to be upright after rotation and transforms coordinates, but when retrieving the cropbox of a page, one still has to apply rotation before making use of it coordinates. Thus, a more complete example would be like this:
using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)))
{
Rectangle cropBox = reader.GetCropBox(1);
int rotation = reader.GetPageRotation(1);
while (rotation > 0)
{
cropBox = cropBox.Rotate();
rotation -= 90;
}
Rectangle bottomRight = new Rectangle(cropBox.GetRight(216), cropBox.Bottom, cropBox.Right, cropBox.GetBottom(146));
EmptyTextBoxSimple(stamper, 1, bottomRight, BaseColor.WHITE);
ColumnText columnText = GenerateTextBox(stamper, 1, bottomRight);
columnText.AddText(new Phrase("Some test text to draw into a text box in the lower right corner of the first page"));
columnText.Go();
}
I am trying to run Countrychunks example from the Chapter 2. The example works but the line: document.Add(Chunk.NEWLINE); does not produce the new line and the loop overwrites the first line. I am posting my code here in case I am doing anything wrong:
public void createCountryChunks(String fileName)
{
iTextSharp.text.Font font;
Document document = new iTextSharp.text.Document();
//PdfWriter.GetInstance(document, new FileStream(fileName)).setInitialLeading(16);
PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
document.Open();
font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 6, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.WHITE);
foreach (var p in myProducts)
{
// add a country to the document as a Chunk
document.Add(new Chunk(p.pr_name));
document.Add(new Chunk(" "));
Chunk id = new Chunk(p.pr_URN.ToString(), font);
// with a background color
id.SetBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
// and a text rise
id.SetTextRise(6);
document.Add(id);
document.Add(Chunk.NEWLINE);
}
document.Close();
}
As you can see the example is a bit different because of the data but the rest is almost the same as the original Java example.
Any suggestions please?
The setInitialLeading call that you weren't able to bring over and was commented out was actually very important. Adding that back in will solve your problems. I really don't like to add properties directly onto my constructed objects so I'm going to do it in two lines:
var w = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
w.InitialLeading = 16;
The code below illustrates a problem I have with iTextSharp. Everything works perfectly. The pdf file is created and appears correct on the screen. When I print the pdf from Adobe Reader X, it looks exactly right but Adobe reports "An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem."
Unfortunately, the file has to be attached to an email and sent to clients. The error message is not a good look and I want to fix it. It happens in all versions of Reader that I have tried, including 10.1.15 installed today.
I have iTextSharp 5.3.4.0 under Windows 7 Pro SP1
private void writeTestDoc()
{
string fname = "test.pdf";
float textWidth = 500;
float leftMgn = 60;
float rubricTop = 720;
float leftPad = 5;
float topPad = 12;
float leading = 0;
BaseFont baseCalibri = BaseFont.CreateFont("c:/windows/fonts/calibri.ttf", BaseFont.WINANSI, true);
Font plainFont = new Font(baseCalibri, 11, Font.NORMAL);
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fname, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
ColumnText ct = new ColumnText(cb);
float boxTop = rubricTop;
ct.SetSimpleColumn(leftMgn + leftPad, boxTop - topPad, leftMgn + textWidth, boxTop, leading, Element.ALIGN_CENTER);
ct.AddText(new Phrase("A test message", plainFont));
ct.Go();
cb.EndText();
document.Close();
}
catch (Exception ex)
{
writeFile("ERROR in writeTestDoc " + ex.Message);
}
}
Remove cb.BeginText(); and cb.EndText();. It's illegal for BT/ET text objects to be nested. Report the place where you've found the documentation that told you to use BeginText()/EndText in combination with ColumnText, so that we can ask the author to correct it from his or her documentation.
I'm developing a System in which I have to add some images to an existing PDF Document.
This works great with iText 5.1.3, but for some reason in a PDF that contains a scanned image it won't add any of the images.
Here's the link to the PDF Document that can't be modified with PdfStamper
and here's the code
PdfReader reader = new PdfReader("Registro celular_OR.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("DocStamped.pdf"));
Image img = Image.getInstance("someImage.jpg");
img.setAbsolutePosition(0, 0);
img.scaleAbsolute(50f, 50f);
PdfContentByte over = null;
int total = reader.getNumberOfPages() + 1;
for(int i = 1; i < total; i++) {
System.out.println("Procesando Pagina: " + i);
over = stamper.getOverContent(i);
over.addImage(img);
over.beginText();
BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
over.setFontAndSize(bf_times, 8);
over.showTextAligned(PdfContentByte.ALIGN_CENTER, "TEXTO PRUEBA", 50, 50, 0);
over.endText();
}
stamper.close();
A PDF page does not need to have its lower left corner at (0, 0). It can be anywhere in the coordinate system. So an A4 page can be (0, 0, 595, 842), but it might as well be (1000, 2000, 1595, 2842).
You are positioning the image at (0, 0):
img.setAbsolutePosition(0, 0);
But the page of this document is defined as (0, 15366, 469, 15728). The image is actually added to the output document, but it's outside the visible area of the page.
You have to get the coordinates of the page to position the image. Inside the loop, do this:
img.setAbsolutePosition(reader.getPageSize(i).getLeft(), reader.getPageSize(i).getBottom());