Attaching a image to a pdf using c# and itextSharp - c#

i am a new to c# programming and i am doing a project that can capture the screen and attach it to a pdf,in my project i need to attach an screenshot of my desktop or application directly to PDF file, i know how to attached a image that has been saved in to the Hard Drive, in this case i used iTextsharp library. what i need to know is there a way to attach the image directly to PDF without saving the image to Hard Drive. till now I can capture my screen and save it to the hard drive. please direct me to a path, Thanx In Advance , code i used is bellow
this is the code i used to capture the screen
string pHotoTime = DateTime.Now.ToString("yyyy-MM-dd, HH mm ss");
Size s = Screen.PrimaryScreen.Bounds.Size;
Bitmap bmp = new Bitmap(s.Width, s.Height);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(0, 0, 0, 90, s);
System.IO.Stream stream = new System.IO.MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
// later:
//bmp.Save(#"C:\Users\NiyNLK\Documents\TESTs\" + pHotoTime + ".jpg");
bmp.Save(#"C:\Users\NiyNLK\Documents\TESTs\MyImage.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = bmp;
below code is used to attached the image
enter code here
iTextSharp.text.Rectangle r = new iTextSharp.text.Rectangle(400, 400);
var doc = new Document(r);
string path = #"c:\users\niynlk\documents\tests";
string Imagepath = #"C:\Users\NiyNLK\Documents\TESTs";
try
{
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path + "/Images.pdf", FileMode.Create));
doc.Open();
doc.Add(new Paragraph("Image"));
Image img = Image.GetInstance(Imagepath + "/MyImage.jpg");
img.ScalePercent(25f);
doc.Add(img);
}
catch (Exception)
{
throw;
}
finally
{
doc.Close();
}

Related

Poor image quality after added to PDF with itextsharp

I want to create a portrait gallery with some photos. In order to achieve this, I add everything I need in a panel and then I get the visual of this panel to add it in a PDF.
My problem is that I managed to create the PDF containing the image, but it is bad quality.
Example 1
Example 2
We see that the outline of peoples is not clear, while in the original photos the outline is very clear.
iTextSharp.text.Document doc = new iTextSharp.text.Document();
panelTombi.AutoScrollPosition = new Point(0, 0);
panelTombi.AutoSize = true;
panelTombi.Refresh();
int width = panelTombi.Width;
int height = panelTombi.Height;
Bitmap MemoryImage = new Bitmap(width, height);
panelTombi.DrawToBitmap(MemoryImage, new System.Drawing.Rectangle(0, 0, width, height));
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance((System.Drawing.Image)MemoryImage, System.Drawing.Imaging.ImageFormat.Jpeg);
image1.ScaleToFit(doc.PageSize);
image1.SetAbsolutePosition(0, PageSize.A4.Height - image1.ScaledHeight - doc.TopMargin);
MemoryImage.Save(Path.GetDirectoryName(sfd.FileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(sfd.FileName) + ".jpeg");
//Save pdf file
PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
doc.Open();
doc.Add(image1);
doc.Close();
As you can see, the image is also saved.
Could you tell me how to fix this image quality problem on the PDF file?
Thank you

Issue capturing windows form drawing to image C#

I'm trying to draw a few objects to a windows form, then create a image of that form and save it to a folder.
This is a two part question... Why isn't the image that is being drawn to the windows form showing up on the created image? Also second question is, how can I create an image of the windows form drawing, from say point 0,0 to point 500,500 without a background....
Here is the code I have at the moment....
Form draw = new Drawing(); // Opens the drawing form
draw.Show();
try
{
//Try to draw something...
System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics = draw.CreateGraphics();
formGraphics.DrawLine(myPen, 0, 0, 500, 500);
myPen.Dispose();
formGraphics.Dispose();
var path = this.outputFolder.Text; // Create variable with output path
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path); // Create path if it doesn't exist
}
using (var bitmap = new Bitmap(draw.Width, draw.Height)) // Creating the .bmp file from windows form
{
draw.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(path + "\\" + i + ".bmp");
}
}
catch { }
Can you see anything wrong here? What seems to be prohibiting the drawings to be saved to a .bmp file?
Thank in advance!
I ended up using the example shown here Saving System.Drawing.Graphics to a png or bmp
Form draw = new Drawing(); // Opens the drawing form
draw.Show();
try
{
var path = this.outputFolder.Text; // Path where images will be saved to
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path); // Create a directory if it does not already exist
}
Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
g.DrawLine(myPen, 0, 0, 1024, 1024);
bitmap.Save(path + "\\" + i + ".png", ImageFormat.Png);
}
catch { }
And that has worked flawlessly for me now :D

How to re-size an image with asp.net C# without saving it

I use this code to re-size images, but my problem is that I have to save the original picture then re-size that! How can I re-size a picture without saving it?
I want to re-size the picture first and then save it.
FileUpload1.SaveAs("saveOriginalFileFirstHere");
string thumbpath = "where resized pic should be saved";
MakeThumbnails.makethumb("saveOriginalFileFirstpath", thumbpath);
public static void makethumb(string savedpath, string thumbpath)
{
int resizeToWidth = 200;
int resizeToHeight = 200;
Graphics graphic;
//Image photo; // your uploaded image
Image photo = new Bitmap(savedpath);
// Image photo = new j
Bitmap bmp = new Bitmap(resizeToWidth, resizeToHeight);
graphic = Graphics.FromImage(bmp);
graphic.InterpolationMode = InterpolationMode.Default;
graphic.SmoothingMode = SmoothingMode.Default;
graphic.PixelOffsetMode = PixelOffsetMode.Default;
graphic.CompositingQuality = CompositingQuality.Default;
graphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);
bmp.Save(thumbpath);
}
Use the InputStream property of the uploaded file instead:
I have modified your code to do so:
EDIT: You really should dispose of your IDisposables, such as your bitmaps and the stream, to avoid memory leakage. I have updated my code, so it will properly dispose these resources after it's done with them.
string thumbpath = "where resized pic should be saved";
MakeThumbnails.makethumb(FileUpload1.InputStream, thumbpath);
public static void makethumb(Stream stream, string thumbpath)
{
int resizeToWidth = 200;
int resizeToHeight = 200;
using (stream)
using (Image photo = new Bitmap(stream))
using (Bitmap bmp = new Bitmap(resizeToWidth, resizeToHeight))
using (Graphics graphic = Graphics.FromImage(bmp))
{
graphic.InterpolationMode = InterpolationMode.Default;
graphic.SmoothingMode = SmoothingMode.Default;
graphic.PixelOffsetMode = PixelOffsetMode.Default;
graphic.CompositingQuality = CompositingQuality.Default;
graphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);
bmp.Save(thumbpath);
}
}
This should work the way you want it to, if it doesn't, or if anything is unclear, please let me know.

MemoryStream is null when creating a new Bitmap from Stream

I am trying to create a Bitmap from a stream that has a PDF document saved with-in the stream, but I keep getting argument null exception. The MS is not null and it is positioned at 0. So I'm lost as to what else to do.
I'm testing the functionality by using a windows forms application sandbox but I cannot get the memory stream to save to a Bitmap.
Can someone point out to me where I'm going wrong?
private async void Form1_Load(object sender, EventArgs e)
{
//4355,4373
IElevation elev = await ElevationManager.GetElevationAsync(4355);
PdfSharp.Pdf.PdfDocument pdfDoc =
await (await AlumCloudPlans.Manager.GetLabelsAsync(elev)).GetPDF(new SheetInfo(/*settings for PDF, Img printing is different*/3, 10, 240, 95, 780, 1000));
System.IO.Stream ms = new MemoryStream();
pdfDoc.Save(ms, false);
ms.Position = 0;
Bitmap bm = new Bitmap(ms); <---------(Error right here, says argument null)
this.AutoScroll = true;
this.pictureBox1.Image = bm;
this.pictureBox1.BackColor = Color.White;
this.Size = new System.Drawing.Size(bm.Width, (bm.Height + 50) / 2);
this.pictureBox1.Size = new System.Drawing.Size(bm.Width, bm.Height + 5);
}
What am i missing here?
You're trying to open stream containing a PDF document, Bitmap constructor is expecting image data. PDFSharp can only create PDF document, but can't render it to image.
To render PDF document to bitmap, you have to use other libraries, e.g. lib-pdf, mupdf-converter or .NET wrapper for Ghostscript.

Bad size image in pdf created with itextsharp

I have a problem to create a pdf with itextsharp from images in .tiff.
Here is some code :
iTextSharp.text.Document d = new iTextSharp.text.Document();
PdfWriter pw = PdfWriter.GetInstance(d, new FileStream(filename, FileMode.Create));
d.Open();
PdfContentByte cb = pw.DirectContent;
foreach (Image img in imgs)
{
d.NewPage();
d.SetPageSize(new iTextSharp.text.Rectangle(0, 0, img.Width, img.Height));
iTextSharp.text.Image timg = iTextSharp.text.Image.GetInstance(img, iTextSharp.text.BaseColor.WHITE);
timg.SetAbsolutePosition(0, 0);
cb.AddImage(timg);
cb.Stroke();
}
d.Close();
It creates the pdf with two pages but the image on the first page is to big.The page have the size of the image but it zoom an the bottom left corner of the image.
It does that only with the tiff image, if I take png, it works fine.
Any solution?
Thanks to the comment of mkl, I found it.
Set the page size (SetPageSize) before the new page command (NewPage)
use like this
string[] validFileTypes = {"tiff"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = false;
if (!isValidFile)
{
Label.Text = "Invalid File. Please upload a File with extension " +
string.Join(",", validFileTypes);
}
else
{
string pdfpath = Server.MapPath("pdf");
Document doc = new Document(PageSize.A4, 0f, 0f, 0f, 0f);
PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create));
doc.Open();
string savePath = Server.MapPath("images\\");
if (FileUpload1.PostedFile.ContentLength != 0)
{
string path = savePath + FileUpload1.FileName;
FileUpload1.SaveAs(path);
iTextSharp.text.Image tiff= iTextSharp.text.Image.GetInstance(path);
tiff.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height);
tiff.SetAbsolutePosition(0,0);
PdfPTable table = new PdfPTable(1);
table.AddCell(new PdfPCell(tiff));
doc.Add(table);
}
doc.Close();
}

Categories

Resources