using System;
using System.Drawing;
using System.Windows.Forms;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
namespace SaveImageToPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSaveToPDF_Click(object sender, EventArgs e)
{
// Check if there is an image in the PictureBox
if (pictureBox1.Image == null)
{
MessageBox.Show("There is no image in the PictureBox to save.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Define the path where the PDF will be saved
string folderPath = @"C:\MyPDFs";
string filePath = System.IO.Path.Combine(folderPath, "Image.pdf");
// Create the folder if it does not exist
if (!System.IO.Directory.Exists(folderPath))
{
System.IO.Directory.CreateDirectory(folderPath);
}
try
{
// Create a new document
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
// Convert the image from PictureBox to a PdfSharp image
using (MemoryStream memoryStream = new MemoryStream())
{
pictureBox1.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
XImage pdfImage = XImage.FromStream(memoryStream);
// Set image position and size
XRect rect = new XRect(0, 0, page.Width, page.Height);
gfx.DrawImage(pdfImage, rect);
}
// Save the document
document.Save(filePath);
MessageBox.Show("Image saved to PDF successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}