how create pdf after image Draw c# - c#

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

Related

System.Drawing.Image to SkiaSharp

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);

Add Watermark image to PDF

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);

iTextSharp BarcodeEAN 13 change width

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);
...

C# Save Bitmap as PDF With iTextSharp

The following code creates a bitmap from a control on the form, and then shows a save dialog to save as a JPEG. Can anyone help with the code to save the Bitmap bm as a PDF with iTextSharp?
Bitmap bm = null;
bm = new Bitmap(this.RCofactorTBS.SelectedTab.Width, this.RCofactorTBS.SelectedTab.Height);
this.RCofactorTBS.SelectedTab.DrawToBitmap(bm, this.RCofactorTBS.SelectedTab.ClientRectangle);
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "JPEG|*.jpeg";
dialog.Title = "Save Test As Jpeg";
dialog.ShowDialog();
if (dialog.FileName != "" && bm != null)
{
bm.Save(dialog.FileName);
}
You can try this
System.Drawing.Image image = System.Drawing.Image.FromFile("Your image file path");
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream("image.pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
doc.Add(pdfImage);
doc.Close();
Referenced from here
public void exportarPDF(Bitmap img){
// System.Drawing.Image image = System.Drawing.Image.FromFile("C://snippetsource.jpg"); // Here it saves with a physical file
System.Drawing.Image image = img; //Here I passed a bitmap
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream("C://image.pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image,
System.Drawing.Imaging.ImageFormat.Jpeg);
doc.Add(pdfImage);
doc.Close();
}

How to crop a tiff image in asp.net

I was looking for a routine by which I can crop tiff image and I got it but it gives many error. Here is the routine:
Bitmap comments = null;
string input = "somepath";
// Open a Stream and decode a TIFF image
using (Stream imageStreamSource = new FileStream(input, FileMode.Open, FileAccess.Read, FileShare.Read))
{
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
using (Bitmap b = BitmapFromSource(bitmapSource))
{
Rectangle cropRect = new Rectangle(169, 1092, 567, 200);
comments = new Bitmap(cropRect.Width, cropRect.Height);
//first cropping
using (Graphics g = Graphics.FromImage(comments))
{
g.DrawImage(b, new Rectangle(0, 0, comments.Width, comments.Height),
cropRect,
GraphicsUnit.Pixel);
}
}
}
When I try to compile it, I get an error. I tried adding references to many assemblies searching google but couldn't resolve it. I got this code from this url:
http://snipplr.com/view/63053/
I am looking for advice.
TiffBitmapDecoder class is from Presentation.Core in another words it is from WPF.
BitmapFromSource isn't method of any .net framework class. You can convert BitmapSource to Bitmap using this code.
private Bitmap BitmapFromSource(BitmapSource bitmapsource)
{
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapsource));
encoder.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}

Categories