I'm trying to add watermark to pdf aready exist in a folder inside my project, I'm using iTextSharp.
Everything is going well and debugging the code is going well, but when finished and I try to open the PDF with watermark just worked on, the file is damage.
Here is my piece of code
string sourceFilePath = Server.MapPath(#"~/uploadfiles/PDFFileName.pdf");
byte[] bytes = File.ReadAllBytes(sourceFilePath);
Bitmap bitmap = new Bitmap(200, 30, System.Drawing.Imaging.PixelFormat.Format64bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.White);
graphics.DrawString(text, new System.Drawing.Font("Arial", 12, FontStyle.Bold), new SolidBrush(Color.Red), new PointF(0.4F, 2.4F));
bitmap.Save(Server.MapPath("~/uploadfiles/Image.jpg"), ImageFormat.Jpeg);
bitmap.Dispose();
var img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/uploadfiles/Image.jpg"));
img.SetAbsolutePosition(200, 400);
PdfContentByte waterMark;
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
PdfStamper stamper = new PdfStamper(reader, stream);
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
waterMark = stamper.GetUnderContent(i);
waterMark.AddImage(img);
}
bytes = stream.ToArray();
}
File.Delete(Server.MapPath("~/uploadfiles/Image.jpg"));
File.WriteAllBytes(sourceFilePath, bytes);
Related
I'm working with PdfSharp to create some pdf files
I am trying to write an image after that save pdf and force download user
but after show box to download and open file, pdf was empty
var foo = new PrivateFontCollection();
foo.AddFontFile(HttpContext.Current.Server.MapPath("~/assets/css/base/fonts/Coustom.ttf"));
var Font_6 = new Font((FontFamily)foo.Families[0], 6f);
StringFormat rf = new StringFormat();
rf.LineAlignment = StringAlignment.Far;
rf.Alignment = StringAlignment.Far;
Brush _RedColor = new SolidBrush(Color.FromArgb(63, 110, 123));
System.Drawing.Image imgBackground = System.Drawing.Image.FromFile(Server.MapPath("../assets/EmptyDoc/Letterhead-FA-A4.jpg"));
int _X = 2300;
int _Y = 450;
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
graphics.DrawString("TEST", Font_6, _RedColor, new PointF((_X - 40), (_Y)), rf);
}
imgBackground.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
byte[] fileContents = null;
MemoryStream memoryStream = new MemoryStream();
document.Save(memoryStream, true);
fileContents = memoryStream.ToArray();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(fileContents);
With PdfSharp, you can add an image as the following :
using (FileStream stream = new FileStream(pngFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
XImage image = XImage.FromStream(stream);
XGraphics graphics = XGraphics.FromPdfPage(this.currentPage);
graphics.DrawImage(image, 0 , 0, 200, 100);
}
you just need to replace pngFile by the full path of your drawing file.
Edit :
After reading your code, you could try to add this after the line XGraphics gfx = XGraphics.FromPdfPage(page); :
XImage image = XImage.FromStream(strm);
XGraphics graphics = XGraphics.FromPdfPage(page);
graphics.DrawImage(image, 0 , 0, 200, 100);
Then replace
imgBackground.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
by
MemoryStream strm = new MemoryStream();
imgBackground.Save(strm, System.Drawing.Imaging.ImageFormat.Png);
Seems the function doesn't accept your Stream, so try with a MemoryStream
I am trying to move my code from using System.Drawing.Image to using SkiaSharp as recommended here.
I trying to find similar operations for working with Tif files from a stream.
Currently, the following is what I have using System.Drawing.Image:
System.Drawing.Image MyImage = System.Drawing.Image.FromStream(inStream);
PdfDocument doc = new PdfDocument();
for (int PageIndex = 0; PageIndex < MyImage.GetFrameCount(FrameDimension.Page); PageIndex++)
{
MyImage.SelectActiveFrame(FrameDimension.Page, PageIndex);
XImage img = XImage.FromGdiPlusImage(MyImage);
var page = new PdfPage();
page.Width = MyImage.Width;
page.Height = MyImage.Height;
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(img, 0, 0, page.Width, page.Height);
}
doc.Save(outStream);
MyImage.Dispose();
My current work with SkiaSharp is the following though it does not work correctly. Note: The following code has the following error and I am trying to figure out why in addition to how to select active frames: Unhandled exception. System.ObjectDisposedException: Cannot access a closed Stream. likely due to SKCodec codec = SkiaSharp.SKCodec.Create(inStream); but I am not sure why.
PdfDocument doc = new PdfDocument();
doc.Info.CreationDate = new DateTime();
using MemoryStream inStream = new MemoryStream(data);
using var imgStream = new SKManagedStream(inStream, false);
using var skData = SKData.Create(imgStream);
using SKCodec codec = SKCodec.Create(skData);
// TODO: codec is null!
for (int PageIndex = 0; PageIndex < codec.FrameCount; PageIndex++)
{
SKImageInfo imageInfo = new SKImageInfo(codec.Info.Width, codec.Info.Height);
// create bitmap stub
using SKBitmap skBitmap = new SKBitmap(imageInfo);
IntPtr pixelsPtr = skBitmap.GetPixels();
// decode particular frame into the bitmap
codec.GetPixels(imageInfo, pixelsPtr, new SKCodecOptions(PageIndex));
// encode bitmap back
using SKData encodedData = skBitmap.Encode(SKEncodedImageFormat.Png, 100);
using Stream frameStream = encodedData.AsStream();
XImage img = XImage.FromStream(frameStream);
var page = new PdfPage();
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(img, 0, 0, page.Width, page.Height);
}
doc.Save(destination);
These are other things I have tried:
Using SKCodecOptions to set the FrameIndex but how would I use it since it used for GetPixels() not Decode().
There are no properties, I found, that control FrameIndex within a SKBitmap.
The additional conversion from Image to XImage is a bit confusing as from the source here, it appears to be a constructor that creates an XImage straight from an Image. I would need to create an XImage from a SkiaSharp.SKBitmap instead I believe thought I'm not quite sure how to do this at the moment such as use an existing method like FromStream() though I don't know the differences between the uses necesarily.
You get the exception because decoding SKBitmap with
SkiaSharp.SKBitmap MyImage = SkiaSharp.SKBitmap.Decode(inStream);
disposes the inStream.
Anyway, to get the particular frame using SkiaSharp, you need to get pixels from the codec:
using MemoryStream inStream = new MemoryStream(data);
PdfDocument doc = new PdfDocument();
doc.Info.CreationDate = new DateTime();
using SKCodec codec = SkiaSharp.SKCodec.Create(inStream);
for (int PageIndex = 0; PageIndex < codec.FrameCount; PageIndex++)
{
SKImageInfo imageInfo = new SKImageInfo(codec.Info.Width, codec.Info.Height);
// create bitmap stub
using SKBitmap skBitmap = new SKBitmap(imageInfo);
IntPtr pixelsPtr = skBitmap.GetPixels();
// decode particular frame into the bitmap
codec.GetPixels(imageInfo, pixelsPtr, new SKCodecOptions(PageIndex));
// encode bitmap back
using SKData encodedData = skBitmap.Encode(SKEncodedImageFormat.Png, 100);
using Stream frameStream = encodedData.AsStream();
XImage img = XImage.FromStream(frameStream);
var page = new PdfPage();
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(img, 0, 0, page.Width, page.Height);
}
doc.Save(destination);
I'm using iTextSharp to create EAN13 barcodes, but I can't change the width of the generated barcode. :(
Changing the height works fine with BarHeight = x
System.Drawing.Image bm = code39.CreateDrawingImage(Color.Black, Color.White);
BarcodeEAN codeEan = new BarcodeEAN();
codeEan.CodeType = Barcode.EAN13;
codeEan.Code = "4035606872510";
codeEan.BarHeight = 130f;
codeEan.X = ... //not working
codeEan.Size = ... //also not working
bm = codeEan.CreateDrawingImage(Color.Black, Color.White);
bm.Save("D:\\temp\\foo.png", ImageFormat.Png);
/* Resizing only stretches the pixels with bad quality */
iTextSharp.text.Image barcode = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Png);
barcode2.ScaleToFit(1200f, 130f);
Found a solution by myself....
But for people with the same problem:
Document doc = new Document();
MemoryStream memStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
doc.Open();
PdfContentByte cb = writer.DirectContent;
BarcodeEAN codeEan = new BarcodeEAN();
codeEan.GenerateChecksum = true;
codeEan.CodeType = Barcode.EAN13;
codeEan.Code = "5449000101549";
codeEan.Font = null;
iTextSharp.text.Image imageEAN = codeEan.CreateImageWithBarcode(cb, null, null);
imageEAN.ScaleAbsolute(150, 50);
imageEAN.SetAbsolutePosition(doc.PageSize.Right - 186f, doc.PageSize.Bottom + 30f);
doc.Add(imageEAN);
...
i am trying to add an image using itextsharp but not having any luck
there are a ton of tutorials for adding an image to a new pdf doc but not and existing pdf so the .add menthod is not avaivlable
i am tring to do use the stamper write method to add image
and i dont get any errors but no image shows up
PdfReader reader = new PdfReader(pdfIn); //get pdf
if (File.Exists(pdfOut)) File.Delete(pdfOut); //reset
FileStream fs = new FileStream(pdfOut, FileMode.Create);
PdfStamper stamper = new PdfStamper(reader, fs);
try
{
// Convert base64string to bytes array
Byte[] bytes = Convert.FromBase64String(base64decode);
iTextSharp.text.Image sigimage = iTextSharp.text.Image.GetInstance(bytes);//
sigimage.SetAbsolutePosition(10, 10);
sigimage.ScaleToFit(140f, 120f);
stamper.Writer.Add(sigimage);
}catch (DocumentException dex){//log exception here
}catch (IOException ioex){//log exception here
}
AcroFields fields = stamper.AcroFields;
//repeat for each pdf form fill field
fields.SetField("agencyName", name.Value);
stamper.FormFlattening = true; // set to true to lock pdf from being editable
stamper.Writer.CloseStream = true;
stamper.Close();
reader.Close();
fs.Close();
I think you try the following adding it to bytes
PdfReader reader = new PdfReader(pdfIn)
FileStream fs = new FileStream(pdfOut, FileMode.Create);
var stamper = new PdfStamper(reader, fs);
var pdfContentByte = stamper.GetOverContent(1);
iTextSharp.text.Image sigimage = iTextSharp.text.Image.GetInstance(bytes);
sigimage.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(sigimage);
using following code you can able to add image to each page in an existing pdf file. ( I use this code for desktop application)
string FileLocation = #"C:\\test\\pdfFileName.pdf"; // file path of pdf file
var uri = new Uri(#"pack://application:,,,/projrct_name;component/View/Icons/funnelGreen.png"); // use image from project/application folder (this image will insert to pdf)
var resourceStream = Application.GetResourceStream(uri).Stream;
PdfReader pdfReader = new PdfReader(FileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "(tempFile).pdf"), FileMode.Create));iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(resourceStream), System.Drawing.Imaging.ImageFormat.Png);
img.SetAbsolutePosition(125, 350); // set the position in the document where you want the watermark to appear.
img.ScalePercent(35f);// not neccessory, use if you want to adjust image
img.ScaleToFit(140f, 100f); // not neccessory, use if you want to adjust image
PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++) // for loop will add image to each page. Based on the condition you can add image to single page also
{
waterMark = stamp.GetOverContent(page);
waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();// closing the pdfStamper, the order of closing must be important
pdfReader.Close();
File.Delete(FileLocation);
File.Move(FileLocation.Replace(".pdf", "(tempFile).pdf"), FileLocation);
I want to insert text into a pdf file with iTextSharp using the code below. Many times it works right but other times it does not work.
FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
PdfReader pdfReader = new PdfReader(pdffile, System.Text.Encoding.UTF8.GetBytes("ownerPassword"));
PdfStamper pdfStamper = null;
// pdfReader.Permissions = 1;
pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
AcroFields testForm = pdfStamper.AcroFields;
PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(index + 1);
string[] formattext = printTxt.Split(new char[] { '\n' });
float lhight = 0;
float abxt = abx;
printTxt= "Hello word";
ft = new FormattedText(printTxt, Color.Black, "Arial", EncodingType.Winansi, true, 9);
Bitmap b = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(b);
Font f = new Font("Arial", 9);
pdfPageContents.BeginText();
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, "ASCII", false);
pdfPageContents.SetFontAndSize(baseFont,20); // 40 point font
pdfPageContents.SetRGBColorFill(0, 0, 0);
float textAngle = 0;
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, printTxt, abx+3, (float)aby + 12 + lhight, textAngle);
pdfPageContents.EndText();
The approach I use to write text on any Pdf file is that I create text fields using a software tool PDF Nitro Professional (You can use some other software to create these fields). Once done you can then use the following pattern of code to write text on those fields.
string pdfTemplate = filePath;
string newFile = outputFilePath;
PdfReader PDFWriter = new PdfReader(pdfTemplate);
PdfStamper pdfStampDocument = new PdfStamper(PDFWriter, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStampDocument.AcroFields;
//For Text field
pdfFormFields.SetField("txtTextFieldName", "First Text");
//For Check Box Field
pdfFormFields.SetField("chkSomeCheckBox", "Yes");
PDFWriter.Close();
pdfStampDocument.Close();
Hope it helps.