How to add an image to whole page with iText 7 C# - c#

I have a .png files which are size of A4. I am adding them to the .pdf. It is working but my image is not covering all .pdf document page and it is leaving the white edges around it. How to cover whole page with my image?
String dest = "C:\\ImagePaged.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document
iText.Layout.Document document2 = new iText.Layout.Document(pdfDoc);
// process and save pages one by one
for (int i = 0; i < 10; i++) //count of .png images
{
iText.IO.Image.ImageData imageData = iText.IO.Image.ImageDataFactory.Create($"C:\\ImagePage{i}.png");
Image image = new Image(imageData);
document2.Add(image);
}
document2.Close();
I guess I need somehow to set page edge parameters. But how to do that.

Pretty sure it is this one
pdfDoc.SetMargins(0, 0, 0, 0);

Related

PDFium - create PDF document from image stream without converting to Bitmap in c#

I am working with PDFium c# tool to create PDF document from PNG image stream.
I have an API which gets multiple image stream objects, I should combine the image streams and create a PDF document and PDF stream. I will need to hit another API to save this document.
I went through the PDFium documentation but, the examples shows how load PDF from Images but, not from stream
Do we need to create a image from Stream to load the PDF or is there any alternate?
Any help is highly appreciated
Thank you In advance
Sample Code I created based on the documentation
public void GeneratePdfFromImageStream(List<Stream> imageStreams, String pdfSaveLocation = null)
{
int pageIndex = 0;
//Initialize C# PDF Library
PdfCommon.Initialize();
//Create a PDF document
using (var doc = PdfDocument.CreateNew())
{
foreach (var imageStream in imageStreams)
{
//I am creating a Bitmap image here, is there a way I can achevie the same withrout creating the image
var image = System.Drawing.Bitmap.FromStream(imageStream, true) as System.Drawing.Bitmap;
//Create empty PdfBitmap
using (PdfBitmap pdfBitmap = new PdfBitmap(image.Width, image.Height, true))
{
using (var g = System.Drawing.Graphics.FromImage(pdfBitmap.Image))
{
//Draw image to PdfBitmap
g.DrawImage(image, 0, 0, image.Width, image.Height);
}
//Create Image object
var imageObject = PdfImageObject.Create(doc, pdfBitmap, 0, 0);
//Calculate size of image in PDF points
var size = CalculateSize(pdfBitmap.Width, pdfBitmap.Height, image.HorizontalResolution, image.VerticalResolution);
//Add empty page to PDF document
doc.Pages.InsertPageAt(pageIndex, size);
//Insert image to newly created page
doc.Pages[pageIndex].PageObjects.Add(imageObject);
//set image matrix
imageObject.Matrix = new FS_MATRIX(size.Width, 0, 0, size.Height, 0, 0);
//Generate PDF page content to content stream
doc.Pages[pageIndex].GenerateContent();
pageIndex++;
}
}
// Save PDF document as "saved.pdf" in no incremental mode
if (string.IsNullOrWhiteSpace(pdfSaveLocation))
doc.Save($"saved_{Guid.NewGuid().ToString()}.pdf", SaveFlags.NoIncremental);
}
}

Creating a PDF using Xamarin Android

I am trying to create a PDF document that can then be open via an external application. The user is selecting an arbitrary number of images which are stored in a List<byte[]>. Disregarding this, I cannot get the following to even create a blank PDF that can be opened. If I try opening the generated PDF, Adobe Reader says that the file has is not supported or has been damaged. I am not sure where the error is occurring since the PDF seems to be generated. I would imagine the problem occurs when trying to write the PDF to the FileStream. What is the issue with the following code?
private void CreatePDFWithImages(List<byte[]> images)
{
// create PDF
PdfDocument pdf = new PdfDocument();
// create a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(612, 792, 0).Create();
// draw image to pag
for (int i = 0; i < images.Count; i++)
{
// start page
PdfDocument.Page page = pdf.StartPage(pageInfo);
// create bitmap from each byte[]
byte[] currentByteArray = images[i];
Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options();
options.InMutable = true;
Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeByteArray(currentByteArray, 0, currentByteArray.Length, options);
// matrix
Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
matrix.PreTranslate(300, 300);
matrix.PreScale(2, 2);
// add image to the page
page.Canvas.DrawBitmap(bitmap, matrix, null);
// finish the page
pdf.FinishPage(page);
}
// save PDF
string path = "/mnt/shared/POC_Documents/temp.pdf";
FileStream fileStream = new FileStream(path, FileMode.Create);
pdf.WriteTo(fileStream);
// close PDF
pdf.Close();
// try to open...
this.OpenPDF(path);
}
In the pageInfo you have to pass page number as 1 instead of 0
and
If you add
fileStream.flush();
after this line
pdf.WriteTo(fileStream);
It will create the pdf

Rotate PDF without truncating contents using PDFsharp

After rotating to portrait view, how might I ensure all content is visible (within page bounds)?
PDFsharp truncates my page when rotated by +90 degrees but not when rotated by -90 degrees.
PdfDocument outputDocument = new PdfDocument();
XPdfForm old = XPdfForm.FromFile(in_filename);
PdfPage newP = outputDocument.AddPage();
if (old.Page.Orientation == PageOrientation.Landscape)
{
old.Page.Rotate= (old.Page.Rotate - 90) % 360;
old.Page.Orientation = PageOrientation.Portrait;
}
newP.Height = old.Page.Height;
newP.Width = old.Page.Width;
// Get a graphics object for page1
XGraphics gfx = XGraphics.FromPdfPage(newP);
// Draw the page identified by the page number like an image
gfx.DrawImage(old, new XRect(0, 0, old.PointWidth, old.PointHeight));
The above works for a few pdf test cases, but I am skeptical it is coincidental/luck
I am using PDFsharp 1.50 beta.
There is a known problem with PDFsharp 1.50 beta with respect to importing rotated PDFs. That problem is still under investigation.
PDF files come in many different variations, therefore it is very difficult to ensure that code works in all cases.
I ended up doing the following:
(Note, this only had to work for a landscape to portrait)
var output = new PdfDocument();
var outputPage = output.AddPage();
using (var stream = new MemoryStream(Convert.FromBase64String(pdfBase64String)))
{
using (var input = XPdfForm.FromStream(stream))
{
outputPage.Height = input.PointWidth;
outputPage.Width = input.PointHeight;
using (var graphics = XGraphics.FromPdfPage(outputPage))
{
graphics.RotateAtTransform(90, new XPoint(input.PointHeight / 2, input.PointHeight / 2));
graphics.DrawImage(input, new XRect(0, 0, input.PointWidth, input.PointHeight));
}
}
}

Variable data on pdf

I want to add variable text and thumbnail images on specific position.
Text with formatting like fontstyles,rotation etc.
iTextSharp.text.pdf.PdfReader reader = null;
Document document = new Document();
PdfWriter writer;
writer = PdfWriter.GetInstance(document,
new FileStream(temp,
FileMode.Create, FileAccess.Write));
reader = new iTextSharp.text.pdf.PdfReader(file);
size = reader.GetCropBox(1);
PdfContentByte cb = writer.DirectContent;
document.NewPage();
PdfImportedPage page = writer.GetImportedPage(reader,
pageNumber);
cb.AddTemplate(page, 0, 0);
document.Close();
This will copy first page to new document. I want to add text and images on new document. how to do that?
Many people will stop reading your question after your first sentence:
I want to Edit existing PDF
If you read the intro of chapter 6 of my book, you'll understand that the word Edit is not the right word to use.
I did read on, and that I saw that you were using Document and PdfWriter to stamp new content on an existing PDF. If you do the effort of reading chapter 6 of my book, you'll understand that this is wrong. You should use PdfStamper instead.
This is one of the examples provided online:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Phrase header = new Phrase("Copy", new Font(FontFamily.HELVETICA, 14));
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
float x = reader.getPageSize(i).getWidth() / 2;
float y = reader.getPageSize(i).getTop(20);
ColumnText.showTextAligned(
stamper.getOverContent(i), Element.ALIGN_CENTER,
header, x, y, 0);
}
stamper.close();
reader.close();
}
You can find these examples on the following URLs:
http://itextpdf.com/sandbox/stamper
http://itextpdf.com/book/chapter.php?id=6
If you need the examples from chapter 6 ported to C#, please visit this URL: http://tinyurl.com/itextsharpIIA2C06
Update
Does PdfStamper support:
font embedding: yes, when done correctly, fonts are embedded,
font size: yes, that's obvious,
font family: you provide the font program, the font program knows the font family,
alignments: for single lines: use showTextAligned(); for text blocks use ColumnText (caveat: read about the difference between text mode and composite mode)
rotation: for single lines, this is only a matter of providing a rotation angle; for text blocks, create a Form XObject and add this object using a rotation,
...

Adding Image watermark to Pdf while Creating it using iTextSharp

Wonder if this possible. Saw many posts on adding watermark after the pdf is created and saved in disk. But during creation of document how do i add a image watermark. I know how to add a image to document. But how do i position it such that it comes at the end of page.
For C#, use this code...
//new Document
Document DOC = new Document();
// open Document
DOC.Open();
//create New FileStream with image "WM.JPG"
FileStream fs1 = new FileStream("WM.JPG", FileMode.Open);
iTextSharp.text.Image JPG = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs1), ImageFormat.Jpeg);
//Scale image
JPG.ScalePercent(35f);
//Set position
JPG.SetAbsolutePosition(130f,240f);
//Close Stream
fs1.Close();
DOC.Add(JPG);
This is essentially identical to adding a header or footer.
You need to create a class that implements PdfPageEvent, and in the OnPageEnd, grab the page's PdfContentByte, and draw your image there. Use an absolute position.
Note: You probably want to derive from PdfPageEventHelper, it has empty implementations of all the page events, so you just need to write the method you actually care about.
Note: Unless your image is mostly transparent, drawing it on top of your page will cover up Many Things. IIRC ("If I Recall Correctly"), PNG and GIF files added by iText will automatically be properly masked, allowing things under them to show through.
If you want to add an opaque image underneath everything, you should override OnStartPage() instead.
This is Java, but converting it is mostly a matter of capitalizing method names and swapping get/set calls for property access.
Image watermarkImage = new Image(imgPath);
watermarkImage.setAbsolutePosition(x, y);
writer.setPageEvent( new MyPageEvent(watermarkImage) );
public MyPageEvent extends PdfPageEventHelper {
private Image waterMark;
public MyPageEvent(Image img) {
waterMark = img;
}
public void OnEndPage/*OnStartPage*/(PdfWriter writer, Document doc) {
PdfContentByte content = writer.getContent();
content.addImage( waterMark );
}
}
This is the accepted answer's port to C#, and what worked for me. I'm using an A4 page size:
Define this BackgroundImagePdfPageEvent class:
public class BackgroundImagePdfPageEvent : PdfPageEventHelper
{
private readonly Image watermark;
public BackgroundImagePdfPageEvent(string imagePath)
{
using (var fs = new FileStream(imagePath, FileMode.Open))
{
watermark = Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Jpeg);
watermark.SetAbsolutePosition(0, 0);
watermark.ScaleAbsolute(PageSize.A4.Width, PageSize.A4.Height);
watermark.Alignment = Image.UNDERLYING;
}
}
public override void OnStartPage(PdfWriter writer, Document document)
{
document.Add(watermark);
}
}
Then, when creating your document:
var doc = new Document(PageSize.A4);
doc.SetMargins(60f, 60f, 120f, 60f);
var outputStream = new MemoryStream();
var writer = PdfWriter.GetInstance(doc, outputStream);
var imagePath = "PATH_TO_YOUR_IMAGE";
writer.PageEvent = new BackgroundImagePdfPageEvent(imagePath);

Categories

Resources