i want to save pdf page as image but no success. i am able to create iText.Layout.Element.Image from pdf with itext7 but stuck here
using var pdfreader = new PdfReader("../../../documents/valid.pdf");
PdfDocument origPdf = new PdfDocument(pdfreader);
PdfPage origPage = origPdf.GetPage(1);
using var stream = new MemoryStream();
using var pdfwriter = new PdfWriter(stream);
PdfDocument pdf = new PdfDocument(pdfwriter);
Document document = new Document(pdf);
PdfFormXObject pageCopy = origPage.CopyAsFormXObject(pdf);
Image image = new Image(pageCopy);
// want to save this image
The iText 7 Image class is (according to JavaDocs) a layout element that represents an image for inclusion in the document model. It essentially can wrap arbitrary contents to be added to the contents of some page (or form XObject, ...) in an image like manner. It is not, however, an arbitrary-content-to-bitmap converter.
If you want to render a page as a bitmap using iText 7 components, consider using the iText 7 Core add-on pdfRender.
Related
I am trying to create a Document object with a custom page size in C# using iText 7.
So far I have tried passing a rectangle using the documentation's definition for resolution of 72 user units per inch:
Rectangle pageSize = new Rectangle(288, 306);
string fullFilePath = "some string";
PdfWriter pdfwriter = new PdfWriter(fullFileNamePDF);
PdfDocument pdf = new PdfDocument(pdfwriter);
pdf.AddNewPage();
Document Doc = new Document(pdf, rect);
However, the code fails compilation with 'cannot convert from iText.Kernel.Geom.Rectangle to iText.Kernel.Geom.PageSize.'
You need to update your code so that you pass in a PageSize to the document constructor instead of the Rectangle directly.
e.g.
// This:
Document Doc = new Document(pdf, rect);
// Should be this:
Document Doc = new Document(pdf, new PageSize(rect));
I need to add some text content to the bottom of an existing .pdf document with iText. I have a working method, but the new content is displayed in the top-left corner, overlapping the existing content:
public PdfDocument GetDocumentWithAppendedContent(string path, string content)
{
var stream = new MemoryStream();
var writer = new PdfWriter(stream);
writer.SetCloseStream(false); // so I can reuse stream to create a readonly document later
var pdfResult = new PdfDocument(new PdfReader(path), writer);
var document = new Document(pdfResult);
var div = new Div().SetMargin(0).SetPadding(0).SetKeepTogether(true);
div.Add(new Paragraph(content));
document.Add(div);
document.Close();
pdfResult.Close();
stream.Position = 0;
return new PdfDocument(new PdfReader(stream)); // return a readonly version
}
How to "move" the content at the bottom of the last page, instead of the beginning of the first? I am new to iText and, surprisingly, can't find a solution online.
You can do it using the code like this.
PdfPage page = doc.GetPage(doc.GetNumberOfPages());
//Create canvas fro the last page
Canvas canvas = new Canvas(page, page.GetPageSize());
//Set fixed position to put the div at the left bottom corner of the canvas
div.SetFixedPosition(0, 0, page.getPageSize().getWidth());
canvas.Add(p);
doc.Close();
I convert the file to PDF using iTextSharp
Creating a new Document and inserting an image into it. How can I transfer width and height of a image to a new pdf? (because the image is compressed)
In the new Document, you can pass the title, keywords, etc. But if you need somewhere to store the old width and height (since the image is compressed), and when reading the PDF to the size of the old pictures. Each page has its own data.
This solution helped. Info contains metadata.
using (var writer = PdfWriter.GetInstance(doc, fs))
{
PdfDictionary info = writer.Info;
PdfName newData = new PdfName($"NewData");
info.Put(newData, new PdfString("any string data"));
}
I'm using IText7 version 7.0.2.2, I'm new with it, I'm trying to merge several pdfs at the same time into one that I'm uploading first, that is working fine, the problem is when I try dynamically to insert some text in one of the pdfs and then merge it, I'm using PdfWriter to write some content into the pdf and then try to merge it, but I'm getting this exception: 'Cannot copy indirect object from the document that is being written.
This is some of the code I'm using:
private byte[] MergePdfForms( HttpPostedFileBase firstPdf, List<SectionAndPdfs> sectionsAndPdf)
{
var dest = new MemoryStream();
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);
firstSourcePdf = new PdfDocument(new PdfReader(keyValuePair.Value), new PdfWriter(dest));
Document document = new Document(firstSourcePdf);
document.Add(new Paragraph(sectionsAndPdf[i].Key).SetBackgroundColor(iText.Kernel.Colors.Color.GRAY));
merger.Merge(firstSourcePdf, 1, subPages); //I'm getting the exception here..
firstSourcePdf.Close();
}
This is a known bug in the class PdfDestination. It was fixed, and will be present in our next release. At the moment you can of course use the snapshot release, which should solve the problem.
i try to draw simple shapes (rectangles, circles..) on an existing PDF using ITextSharp, without having to create a new PDF. I found a post who talk about this issue (itextsharp modify existing pdf (no new source pdf) and add watermark) and i would like to know if anybody could tell me more about it.
my aim is to modify a pdf by adding a circle on it, the current solution involve the creation of a new PDF (Itextsharp). Is it possible to add a circle on a PDF without creating a new one ?
Thank you.
J.
You can't read a file and write to it simultaneously. Think of how Word works: you can't open a Word document and write directly to it. Word always creates a temporary file, writes the changes to it, then replaces the original file with it and then throws away the temporary file.
You can do that too:
read the original file with PdfReader,
create a temporary file for PdfStamper, and when you're done,
replace the original file with the temporary file.
Or:
read the original file into a byte[],
create PdfReader with this byte[], and
use the path to the original file for PdfStamper.
This second option is more dangerous, as you'll lose the original file if you do something that causes an exception in PdfStamper.
As for adding content with PdfStamper, please take a look at the section entitled "Manipulating existing PDFs" in the free ebook The Best iText Questions on StackOverflow. You'll find questions such as:
How to add a watermark to a PDF file?
How do I insert a hyperlink to another page with iTextSharp in an existing PDF?
iText - How to stamp image on existing PDF and create an anchor
...
All of these examples add content by creating a PdfContentByte instance like this:
PdfContentByte canvas = stamper.getOverContent(pagenumber);
It's this canvas you need to use when drawing a circle on the page with page number pagenumber. It is important that you use the correct coordinates when you do this. That's explained here: How to position text relative to page using iText?
Update:
Json posted the following code in the comments:
string oldFile = #"C:\Users\ae40394\Desktop\hello.pdf";
string newFile = #"C:\Users\ae40394\Desktop\NEW.pdf";
// creating a reader with the original PDF
PdfReader reader = new PdfReader(oldFile);
Rectangle rect = reader.GetPageSize(1);
FileStream fs = new FileStream(newFile,FileMode.Create);
using (PdfStamper stamper = new PdfStamper(reader, fs)) {
// modify the pdf content
PdfContentByte cb = stamper.GetOverContent(1);
cb.SetColorStroke(iTextSharp.text.BaseColor.GREEN);
cb.SetLineWidth(5f);
cb.Circle(rect.GetLeft() + 30, rect.GetBottom() + 30 ,20f);
cb.Stroke();
}
reader.Close();
File.Replace(#"C:\Users\ae40394\Desktop\NEW.pdf", #"C:\Users\ae40394\Desktop\hello.pdf", #"C:\Users\ae40394\Desktop\hello.pdf.bac");
I slightly adapted the code, because:
There is no need for a Document object,
The stamper is closed when using is closed,
When the stamper is closed, so is the FileStream
the coordinates of the circle were hard coded. I used the page size to make sure they are made relative to the origin of the coordinate system, although to be sure, you may also want to check if there's a Crop Box.
You CAN read a file and write to it simultaneously.
Here is an example:
private void button4_Click(object sender, EventArgs e)
{
using (PdfReader pdfReader = new PdfReader(new FileStream(pdfInput, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(pdfInput, FileMode.Open, FileAccess.Write, FileShare.None)))
{
PdfContentByte canvas = pdfStamper.GetUnderContent(1);
canvas.SetColorFill(BaseColor.YELLOW);
canvas.Rectangle(36, 786, 66, 16);
canvas.Fill();
}
}
// PDF Datei im Anschluss anzeigen/öffnen
System.Diagnostics.Process.Start(pdfInput);
}
string oldFile = #"C:\...6166-21.pdf";
string newFile = #"C:\...NEW.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
cb.SetColorStroke(iTextSharp.text.BaseColor.GREEN);
cb.Circle(150f, 150f, 50f);
cb.Stroke();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();