Print the panel's content to a PDF - c#

I create a form:
The "button1" add new content to my panel and there is a scrollbar:
I want to save the content of my panel to a PDF. It's not very hard:
Bitmap MemoryImage;
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "PDF file|*.pdf", ValidateNames = true })
{
if (sfd.ShowDialog() == DialogResult.OK)
{
iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
try
{
panelTombi.AutoSize = true;
panelTombi.Refresh();
int width = panelTombi.Width;
int height = panelTombi.Height;
MemoryImage = new Bitmap(width, height);
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, 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.Png);
image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
MemoryImage.Save("ttt.png"); // Pour voir l'image qui devrait être ajoutée dans le PDF
//Save pdf file
PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
doc.Open();
doc.Add(image1);
panelTombi.AutoSize = false;
panelTombi.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
doc.Close();
}
}
}
I save the content to a Bitmap, I create a PDF instance, I add the image to the PDF, I close the PDF.
In order to test that, I save the Bitmap to an image and it works:
but there is a problem in the PDF ...
The image seems to have a big zoom, the left part is missing as well as the bottom of the image.
Would you know where the error lies please?
I prefer to have a PDF to save on my computer because it is much easier to see the number of pages needed.
thank you in advance

Add this code only and create perfect pdf
image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
image1.ScaleToFit(PageSize.A4.Rotate().Width - 50f, PageSize.A4.Rotate().Height - 50f);

Related

how create pdf after image Draw 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

How to delete image after save using Bitmap object with Selenium c#?

I am using selenium C# to take screenshots. Convert as Bitmap and then Save to specific path. After save complete. I want to delete that same screenshot. It doesn't allow me to delete and throw the file that is being used by another process.
Below is my code:
public Bitmap GetScreenshot(IWebDriver driver)
{
//Take Screenshot
Screenshot screenshot = (driver as ITakesScreenshot).GetScreenshot();
//Convert Screenshot to Bitmap
var img = Image.FromStream(new MemoryStream(screenshot.AsByteArray)) as Bitmap;
return img;
}
I used above function like this:
var img = GetScreenshot(driver);
seleniumExtras.SaveImageAsPDF(img, "fullpage.jpeg");
Here is the function SaveImageAsPDF:
public void SaveImageAsPDF(Bitmap imageData, string ImagePath)
{
imageData.Save(ImagePath, ImageFormat.Jpeg);
imageData.Dispose();
//Save as PDF
System.Drawing.Image image = System.Drawing.Image.FromFile(ImagePath);
iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4);
doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(ImagePath.Replace(".jpeg", ".pdf"), FileMode.Create));
doc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
//pdfImage.SetAbsolutePosition(0, 0); // set the position to bottom left corner of pdf
pdfImage.ScaleAbsolute(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); // set the height and width of image to PDF page size
pdfImage.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height);
doc.Add(pdfImage);
doc.Close();
doc.Dispose();
//Delete image file after PDF created
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
//imageData.Dispose();
imageData.Dispose();
if (File.Exists(ImagePath))
File.Delete(ImagePath);
}

How to insert a dynamically generated bitmap into PDF document using PDFsharp?

I am trying to use PDFsharp to insert a dynamically generated bitmap of a QR Code in to a PDF document. I don't want to save the bitmap to the file but just want to insert it into the PDF. The problem I'm having is the DrawImage command is looking for a string where the image file is located. But I don't want to save the file, I just want to insert it into the PDF document. Is there a way of doing this?
var QRCode_BMP = _generalCode.QR_CodeGenerator(AddReviewPath); //This generates the bitmap
MemoryStream streamQR = new MemoryStream();
QRCode_BMP.Save(streamQR, System.Drawing.Imaging.ImageFormat.Jpeg); //save bitmap into memory stream in jpeg format System.Drawing.Image QR_Jpeg = System.Drawing.Image.FromStream(streamQR);// save memory stream to image file
XImage xImage = XImage.FromGdiPlusImage(QR_Jpeg);
gfx = XGraphics.FromPdfPage(page);
DrawImage(gfx, xImage, 0, 0, 100, 100); //This is not working
QRCode_BMP.Dispose();
streamQR.Close();
gfx.Dispose();
You create a QR code in QRCode_BMP and then you create an XImage from QR_Jpeg and write it is not working.
QRCode_BMP is only used to create a stream that is never used. We don't see where QR_Jpeg is coming from.
Provide a complete sample.
BTW: You can use XImage.FromStream to use the stream you created.
P.S.: IMHO JPEG is a bad choice for QR codes. Just use BMP and PDFsharp will use a lossless compression.
This is how I made it work;
PdfDocument pdf = PdfGenerator.GeneratePdf("<b>some html here</b>", PageSize.A4);
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode("some text here", QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(10);
PdfPage page = pdf.Pages[0]; //I will add it to 1st page
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
XImage image = XImage.FromGdiPlusImage(qrCodeImage); //you can use XImage.FromGdiPlusImage to get the bitmap object as image (not a stream)
gfx.DrawImage(image, 50, 50, 150, 150);
//save your pdf, dispose other objects
Using XImage.FromStream like #I liked the old Stack Overflow mentioned, in your posted code you should be able to just use:
var QRCode_BMP = _generalCode.QR_CodeGenerator(AddReviewPath); //This generates the bitmap
MemoryStream streamQR = new MemoryStream();
QRCode_BMP.Save(streamQR, System.Drawing.Imaging.ImageFormat.Jpeg); //save bitmap into memory stream in jpeg format System.Drawing.Image QR_Jpeg = System.Drawing.Image.FromStream(streamQR);// save memory stream to image file
//XImage xImage = XImage.FromGdiPlusImage(QR_Jpeg); // <-- Removed
gfx = XGraphics.FromPdfPage(page);
gfx.DrawImage(XImage.FromStream(streamQR), 0, 0, 100, 100); // <-- Added
//DrawImage(gfx, xImage, 0, 0, 100, 100); //This is not working // <-- Removed
QRCode_BMP.Dispose();
streamQR.Close();
gfx.Dispose();
For general usage of streams for XGraphics.DrawImage (library PDFSharp) here's some code I use to print SVG vector path data to PDF:
System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
// YouTube like button SVG vector path data:
path.Data = Geometry.Parse("M12.42,14A1.54,1.54,0,0,0,14,12.87l1-4.24C15.12,7.76,15,7,14,7H10l1.48-3.54A1.17,1.17,0,0,0,10.24,2a1.49,1.49,0,0,0-1.08.46L5,7H1v7ZM9.89,3.14A.48.48,0,0,1,10.24,3a.29.29,0,0,1,.23.09S9,6.61,9,6.61L8.46,8H14c0,.08-1,4.65-1,4.65a.58.58,0,0,1-.58.35H6V7.39ZM2,8H5v5H2Z");
// Visual check of the path:
// https://yqnn.github.io/svg-path-editor/
// Color area bordered through path of SVG vector:
path.Fill = new SolidColorBrush(Colors.Black);
// Upscale path, if final image is blurry:
double scale = 2;
path.RenderTransform = new ScaleTransform(scale, scale);
Rect bounds = path.Data.GetRenderBounds(null);
// Increase render bounds (here: "+ 4"), if parts of the path in the final image are cut off (test it with "scale = 1" before upscaling):
bounds.Width = (bounds.Width + 4) * scale;
bounds.Height = (bounds.Height + 4) * scale;
path.Measure(bounds.Size);
path.Arrange(bounds);
RenderTargetBitmap bitmap = new RenderTargetBitmap(
(int)bounds.Width, (int)bounds.Height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(path);
// Transparent areas are replaced with black pixels when using a "BmpBitmapEncoder", so instead use a "PngBitmapEncoder":
PngBitmapEncoder encoderPng = new PngBitmapEncoder();
encoderPng.Frames.Add(BitmapFrame.Create(bitmap));
using (MemoryStream stream = new MemoryStream())
{
encoderPng.Save(stream);
// Draw image to PDF using "XGraphics.DrawImage":
gfx.DrawImage(XImage.FromStream(stream), 10, 100, 14.05, 12.05);
}

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

Overlay text over an image background and convert to PDF

Using .NET, I want to programmatically create a PDF which simply consists of a background image with two labels over it with different fonts and positioning. I have read about existing PDF libraries, but don't know (if applicable) which one is the easiest for such a simple task.
Anyone care to guide me?
P.D.: I do not want to create the PDF with a generated image that already overlays the text over the background image.
Edit: This is the final working code:
public string Create()
{
if (!Directory.Exists(ApplicationImagePath))
{
Directory.CreateDirectory(ApplicationImagePath);
}
// Smart card
var doc = new Document(PageSize.GetRectangle("153 242.65"), 0, 0, 0, 0);
using (var stream = File.Create(filepath))
{
var writer = PdfWriter.GetInstance(doc, stream);
doc.Open();
var image = Image.GetInstance(CarnetData.Frame, ImageFormat.Png);
image.Alignment = Element.ALIGN_CENTER;
image.ScaleToFit(153, 242.65f);
doc.Add(image);
BaseFont font = BaseFont.CreateFont(GetFontPath(CarnetConfiguration.FontType), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
font.PostscriptFontName = CarnetConfiguration.FontType.ToString();
float verticalPosition = writer.GetVerticalPosition(false);
var pName = new Paragraph(CarnetData.Name, new Font(font, FontData.EmployeeFont.SizeInPoints))
{
SpacingBefore = verticalPosition - 51f,
MultipliedLeading = 1.1f,
Alignment = Element.ALIGN_CENTER
};
doc.Add(pName);
var pDepartment = new Paragraph(CarnetData.Department, new Font(font, FontData.DepartmentFont.SizeInPoints))
{
SpacingBefore = 1.5f,
MultipliedLeading = 1.2f,
Alignment = Element.ALIGN_CENTER
};
doc.Add(pDepartment);
writer.ViewerPreferences = PdfWriter.PageModeUseNone + PdfWriter.CenterWindow + PdfWriter.PageLayoutSinglePage;
doc.Close();
}
return filepath;
}
Thanks for the help. :)
iTextSharp is a great library you could use, very simple and intuitive:
var doc = new Document();
using (var stream = File.Create("output.pdf"))
{
var writer = PdfWriter.GetInstance(doc, stream);
doc.Open();
doc.Add(Image.GetInstance(#"c:\foo\test.png"));
var cb = writer.DirectContent;
cb.BeginText();
cb.SetTextMatrix(100, 220);
var font = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
cb.SetFontAndSize(font, 12);
cb.ShowText("Hello World");
cb.EndText();
cb.BeginText();
cb.SetTextMatrix(100, 250);
cb.ShowText("Some other text");
cb.EndText();
doc.Close();
}
Use iTextSharp. Free.
#binaryhowl - You can try Syncfusion PDF. It is great component with excellent support
http://asp.syncfusion.com/sfaspnetsamplebrowser/9.1.0.20/Web/Pdf.Web/samples/4.0/

Categories