I’m using WinForms. In my form I have a picturebox that displays tif image documents. I’m using PdfSharp as one of my references to convert the tif documents to pdf documents. The good news is I can convert one of the tif pages that is currently displayed in the picturebox.
The problem is when I have a tif document that has more than 1 page, I cannot convert them all into on single Pdf file. For example if I have a tif document image that contains 5 pages, I would want to press a button and convert all those 5 tif pages into 5 pdf pages.
For testing here is a tif document with 5 pages.
Link: http://www.filedropper.com/sampletifdocument5pages
My Code:
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
private string srcFile, destFile;
bool success = false;
private void Open_btn_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(dlg.FileName);
lbl_SrcFile.Text = dlg.FileName;
}
dlg.Dispose();
}
private void Save_btn_Click(object sender, EventArgs e)
{
SaveImageToPDF();
}
private void SaveImageToPDF()
{
try
{
string source = lbl_SrcFile.Text;
string savedfile = #"C:\image\Temporary.tif";
pictureBox1.Image.Save(savedfile);
source = savedfile;
string destinaton = #"C:\image\new_PDF_TIF_Document.pdf";
PdfDocument doc = new PdfDocument();
var page = new PdfPage();
XImage img = XImage.FromFile(source);
if (img.Width > img.Height)
{
page.Orientation = PageOrientation.Landscape;
}
else
{
page.Orientation = PageOrientation.Portrait;
}
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]); xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
img.Dispose(); //dispose img in order to free the tmp file for deletion (Make sure the PDF file is closed thats being used)
success = true;
MessageBox.Show(" File saved successfully! \n\nLocation: C:\\image\\New PDF Document.pdf", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process.Start(destinaton);
File.Delete(savedfile);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
[Edit] Added full working code...with paths hard-coded.
try
{
string destinaton = #"C:\Temp\Junk\new_PDF_TIF_Document.pdf";
Image MyImage = Image.FromFile(#"C:\Temp\Junk\Sample tif document 5 pages.tiff");
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();
if (img.Width > img.Height)
{
page.Orientation = PageOrientation.Landscape;
}
else
{
page.Orientation = PageOrientation.Portrait;
}
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(img, 0, 0);
}
doc.Save(destinaton);
doc.Close();
MyImage.Dispose();
MessageBox.Show("File saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
It's been a while since I've used PdfSharp, but you should be able to call the GetFrameCount method on your image, which will tell you how many pages it has.
Then you can use the SelectActiveFrame method to choose which page is active.
PDFsharp-gdi
public static void ToPDF() {
try
{
PdfDocument doc = new PdfDocument();
string source = #"D:\TIF\bb.tif";
string destinaton = #"D:\TIF\bb.pdf";
Image img = Image.FromFile(source);
for (int PageIndex = 0; PageIndex < img.GetFrameCount(FrameDimension.Page); PageIndex++)
{
img.SelectActiveFrame(FrameDimension.Page, PageIndex);
XImage xImg = XImage.FromGdiPlusImage(img);
double width = Math.Ceiling((double)(xImg.Width * 72) / 96);
double height = Math.Ceiling((double)(xImg.Height * 72) / 96);
var page = new PdfPage();
if (xImg.Width > xImg.Height)
{
page.Orientation = PdfSharp.PageOrientation.Landscape;
}
else
{
page.Orientation = PdfSharp.PageOrientation.Portrait;
}
page.Width = width;
page.Height = height;
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(xImg, 0, 0, width, height);
}
doc.Save(destinaton);
doc.Close();
img.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
Related
I am trying to convert every pages of a pdf into separate pdf files. I have given the range of 6 to create 6 separate pdf files.
using System;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Windows.Forms;
using System.IO;
namespace Learning.SpitPdfApp {
public partial class MainForm : Form {
public MainForm() {
InitializeComponent();
}
private void SplitPdfButton_Click(object sender, EventArgs e) {
MainForm objMainForm = new MainForm();
objMainForm.ExtractPage(SourceTextBox.Text, DestinationTextBox.Text);
}
public void ExtractPage(string sourcePath, string outputPath) {
int startPage = 1;
PdfReader objReader = new PdfReader(sourcePath+".pdf");
int endPage = 6;
Document objDocument = new Document(objReader.GetPageSizeWithRotation(startPage));
objDocument.Open();
for (int index = startPage; index <= endPage; index++) {
PdfCopy pdfCopyProvider = new PdfCopy(objDocument, new FileStream(outputPath+""+index+".pdf", FileMode.Create));
PdfImportedPage importedPage = pdfCopyProvider.GetImportedPage(objReader, index);
pdfCopyProvider.AddPage(importedPage);
}
objDocument.Close();
objReader.Close();
MessageBox.Show(#"Splitting successful!");
}
}
}
But it is throwing a null reference pointer exception. I can't figure out the problem i've caused.
Any help would be appreciated.
Thanks in advance.
This extracts page without any exception.
public void ExtractPage(string sourcePdfPath, string outputPdfPath, int pageNumber)
{
PdfReader reader = null;
Document document = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage = null;
try
{
// Intialize a new PdfReader instance with the contents of the source Pdf file:
reader = new PdfReader(sourcePdfPath);
// Capture the correct size and orientation for the page:
document = new Document(reader.GetPageSizeWithRotation(pageNumber));
// Initialize an instance of the PdfCopyClass with the source
// document and an output file stream:
pdfCopyProvider = new PdfCopy(document,
new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
document.Open();
// Extract the desired page number:
importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber);
pdfCopyProvider.AddPage(importedPage);
document.Close();
reader.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Why are you creating instance of same form to call ExtractPage Method? when you can call it without creating a new instance?
Here is a fix for your code:
private void SplitPdfButton_Click(object sender, EventArgs e)
{
try
{
ExtractPage(SourceTextBox.Text, DestinationTextBox.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void ExtractPage(string sourcePath, string outputPath)
{
int startPage = 1;
int endPage = 6;
for (int index = startPage; index <= endPage; index++)
{
PdfReader objReader = new PdfReader(sourcePath + ".pdf");
Document objDocument = new Document(objReader.GetPageSizeWithRotation(startPage));
string destination = Path.Combine(outputPath, index + ".pdf");
PdfCopy pdfCopyProvider = new PdfCopy(objDocument, new FileStream(destination, FileMode.Create));
objDocument.Open();
PdfImportedPage importedPage = pdfCopyProvider.GetImportedPage(objReader, index);
pdfCopyProvider.AddPage(importedPage);
objDocument.Close();
objReader.Close();
}
MessageBox.Show(#"Splitting successful!");
}
I am writing a winform application in C# to open an image and overlay another image on top of it.
The bottom image is a .jpg and the top one is a .bmp converted from .svg. The .jpg and the .svg are the only ones I want to keep in the folder. The .bmp works as a temp.
I was using the following code to overlay the images. But I am having trouble to delete the temp .bmp as it is used by another process. I think it is this combine code still have access to the last .bmp file.
Could anyone help me on this? Thanks.
private void buttonSearch_Click(object sender, EventArgs e)
{
FailInfo.Text = "";
deletebmp(strFolderPath);
...
// Check if the specified front image exists. Yes, show the file name and convert SVG to BMP. No, show the error msg.
if (File.Exists(strFilePathF))
{
labelFront.Text = strFileNameF;
var svgConvert = SvgDocument.Open(svgFilePathF);
svgConvert.Draw().Save(bmpFilePathF);
pictureBoxFront.Image = Image.FromFile(strFilePathF);
}
else
{
labelFront.Text = "Couldn't find the file!";
pictureBoxFront.Image = null;
}
// Check if the specified back image exists. Yes, show the file name and convert SVG to BMP. No, show the error msg.
if (File.Exists(strFilePathBF))
{
labelBack.Text = strFileNameBF;
strFilePathB = strFilePathBF;
pictureBoxBack.Image = Image.FromFile(strFilePathB);
labelResult.Text = "FAIL";
labelResult.BackColor = Color.FromArgb(255, 0, 0);
var svgConvert = SvgDocument.Open(svgFilePathBF);
bmpFilePathB = strFolderPath + strFileNameBF + ".bmp";
svgConvert.Draw().Save(bmpFilePathB);
svgFilePathB = svgFilePathBF;
inspectionres(svgFilePathB);
labelreason.Visible = true;
}
else if (File.Exists(strFilePathBP))
{
labelBack.Text = strFileNameBP;
strFilePathB = strFilePathBP;
pictureBoxBack.Image = Image.FromFile(strFilePathB);
labelResult.Text = "PASS";
labelResult.BackColor = Color.FromArgb(0, 255, 0);
var svgConvert = SvgDocument.Open(svgFilePathBP);
bmpFilePathB = strFolderPath + strFileNameBP + ".bmp";
svgConvert.Draw().Save(bmpFilePathB);
svgFilePathB = svgFilePathBP;
inspectionres(svgFilePathB);
labelreason.Visible = false;
}
else
{
labelBack.Text = "Couldn't find the file!";
pictureBoxBack.Image = null;
labelResult.Text = "ERROR";
labelResult.BackColor = Color.FromArgb(0, 255, 255);
labelreason.Visible = false;
}
}
//
// Overlay the SVG file on top of the JPEG file
//
private Bitmap Combine(string jpegFile, string bmpFile)
{
Image image1 = Image.FromFile(jpegFile);
Image image2 = Image.FromFile(bmpFile);
Bitmap temp = new Bitmap(image1.Width, image1.Height);
using (Graphics g = Graphics.FromImage(temp))
{
g.DrawImageUnscaled(image1, 0, 0);
g.DrawImageUnscaled(image2, 0, 0);
}
return temp;
}
//
// Show the overlaid graphic in the picturebox
//
private void checkBoxOverlay_CheckedChanged(object sender, EventArgs e)
{
try
{
if (FindFront)
if (checkBoxOverlay.Checked)
pictureBoxFront.Image = Combine(strFilePathF, bmpFilePathF);
else
pictureBoxFront.Image = Image.FromFile(strFilePathF);
else
pictureBoxFront.Image = null;
if (FindBack)
if (checkBoxOverlay.Checked)
pictureBoxBack.Image = Combine(strFilePathB, bmpFilePathB);
else
pictureBoxBack.Image = Image.FromFile(strFilePathB);
else
pictureBoxBack.Image = null;
}
catch (Exception ex)
{
MessageBox.Show("Error loading image" + ex.Message);
}
}
//
// Option of changing the image folder
//
private void buttonPath_Click(object sender, EventArgs e)
{
FolderBrowserDialog FolderBrowserDialog1 = new FolderBrowserDialog();
if (FolderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
strFolderPath = FolderBrowserDialog1.SelectedPath + "\\";
}
}
//
// Pull the inspection result info from the SVG file
//
private void inspectionres(string filename)
{
XDocument document = XDocument.Load(filename);
XElement svg_Element = document.Root;
string sb = null;
var faillist = (from svg_path in svg_Element.Descendants("{http://www.w3.org/2000/svg}text") select svg_path).ToList();
foreach (var item in faillist)
{
sb += item.ToString();
}
}
//
// Delete all the .bmp files generated from .svg files
//
private void deletebmp(string path)
{
// Unload the images from the picturebox if applicable
pictureBoxFront.Image = null;
pictureBoxBack.Image = null;
string[] files = Directory.GetFiles(path, "*.bmp");
for (int i = 0; i < files.Length; i ++ )
File.Delete(files[i]);
}
}
Image implements IDisposable, so simply setting the pictureBox.Image property to null will not release resources (in your case, the file). Your Combine method also leaves the images open. You have to call Dispose before attempting to delete the file:
Image image1 = Image.FromFile(path1);
File.Delete(path1); // error - file is locked
Image image2 = Image.FromFile(path2);
image2.Dispose();
File.Delete(path2); // works
An alternative approach (and I assume you're using WinForms here, in WPF it's a little different) would be to load the bitmap from the file manually (using FromStream). Then, you can close the stream immediately and delete the file:
Image image;
using (Stream stream = File.OpenRead(path))
{
image = System.Drawing.Image.FromStream(stream);
}
pictureBox.Image = image;
File.Delete("e:\\temp\\copy1.png"); //works
Vesan's answer didn't helped me so I found an different solution.
So I can safe/open an image and if I want instantly delete the image.
i used it for my dataGridView_SelectionChanged:
private void dataGridViewAnzeige_SelectionChanged(object sender, EventArgs e)
{
var imageAsByteArray = File.ReadAllBytes(path);
pictureBox1.Image = byteArrayToImage(imageAsByteArray);
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
All above answers are perfectly fine, but I've got a different approach.
Using Image abstract class, you will not get quite a lot of options for manipulating and resizing image.
Rather you do as follows:-
Bitmap img = new Bitmap(item);
img.SetResolution(100, 100);
Image imgNew = Image.FromHbitmap(img.GetHbitmap());
pictureBox1.Image = imgNew;
img.Dispose();
I want to download a PDF file from server side into client system. A Report page is changed into PDF file and saved into a project folder that is on server side. Here the problem is that when I access it from client system and try to generate PDF file then I am not sure whether it has successfully generated a PDF file into server side project folder or not and it is not automatically downloaded into the client system. But when I run project from local system then it is working correctly.
Here I post my code, please check it and please give me a solution for this, I need it very much
My code is:
protected void btn_print_Click(object sender, EventArgs e)
{
try
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
int width = 850;
int height = 550;
Thumbnail1 thumbnail = new Thumbnail1(url, 990, 1000, width, height);
Bitmap image = thumbnail.GenerateThumbnail();
image.Save(Server.MapPath("~") + "/Dwnld/Thumbnail.bmp");
imagepath = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.bmp";
imagepath1 = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.pdf";
convetToPdf();
}
catch (Exception)
{
throw;
}
}
string imagepath = null;
string imagepath1 = null;
public void convetToPdf()
{
PdfDocument doc = new PdfDocument();
System.Drawing.Size size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);
PdfPage pdfPage = new PdfPage();
pdfPage.Orientation = PageOrientation.Landscape;
doc.Pages.Add(pdfPage);
// XSize size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4)
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
XImage img = XImage.FromFile(imagepath);
xgr.DrawImage(img, 0, 0);
doc.Save(imagepath1);
xgr.Dispose();
img.Dispose();
doc.Close();
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
string FilePath = imagepath1;
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
}
public class Thumbnail1
{
public string Url { get; set; }
public Bitmap ThumbnailImage { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int BrowserWidth { get; set; }
public int BrowserHeight { get; set; }
public Thumbnail1(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
this.Url = Url;
this.BrowserWidth = BrowserWidth;
this.BrowserHeight = BrowserHeight;
this.Height = ThumbnailHeight;
this.Width = ThumbnailWidth;
}
public Bitmap GenerateThumbnail()
{
Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return ThumbnailImage;
}
private void GenerateThumbnailInteral()
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.Navigate(this.Url);
webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete) System.Windows.Forms.Application.DoEvents();
webBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser webBrowser = (WebBrowser)sender;
webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
webBrowser.ScrollBarsEnabled = false;
this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
webBrowser.BringToFront();
webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds);
this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
}
}
protected void CreateThumbnailImage(object sender, EventArgs e)
{
}
One potential problem with this code is that you're writing to the same files for every request. If there are multiple requests at the same time, some of them might fail.
To solve this you could write to the response stream directly, i.e.
protected void btn_print_Click(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
int width = 850;
int height = 550;
Thumbnail1 thumbnail = new Thumbnail1(url, 990, 1000, width, height);
using (Bitmap image = thumbnail.GenerateThumbnail())
convertToPdf(image);
}
public void convertToPdf(Image image)
{
using (PdfDocument doc = new PdfDocument())
{
System.Drawing.Size size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);
PdfPage pdfPage = new PdfPage();
pdfPage.Orientation = PageOrientation.Landscape;
doc.Pages.Add(pdfPage);
using (XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]))
{
using (XImage img = XImage.FromGdiPlusImage(image))
{
xgr.DrawImage(img, 0, 0);
using (MemoryStream stream = new MemoryStream())
{
doc.Save(stream, false);
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Length", stream.Length.ToString());
stream.WriteTo(Response.OutputStream);
}
}
}
}
Response.End();
}
Edit Modified answer to use using statements to release resources.
I have an OpenFileDialog in my WinForm and I want when to select an image to limit the image's size in 100 Ko and the Dimensions in 350x350.
How can I do that ??
private bool ValidFile(string filename, long limitInBytes, int limitWidth, int limitHeight)
{
var fileSizeInBytes = new FileInfo(filename).Length;
if(fileSizeInBytes > limitInBytes) return false;
using(var img = new Bitmap(filename))
{
if(img.Width > limitWidth || img.Height > limitHeight) return false;
}
return true;
}
private void selectImgButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(ValidFile(openFileDialog1.FileName, 102400, 350, 350))
{
// Image is valid and U can
// Do something with image
// For example set it to a picture box
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
}
else
{
MessageBox.Show("Image is invalid");
}
}
}
It depends on what types of images you need to support. For most common types (bmp, jpg, png), you can easily retrieve image info:
string filename = // get it from OpenFileDialog
if (new FileInfo(filename).Length > SOME_LIMIT)
{
MessageBox.Show("!!!");
}
else
{
Image img = Image.FromFile(filename);
MessageBox.Show(string.Format("{0} x {1}", img.Width, img.Height));
}
If you need more extensive support for many image formats, then I suggest using a library like ImageMagick.NET
put this as global variable
int imgSize = 0
private void button1_Click(object sender, EventArgs e)
{
Image imageFile;
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
dlg.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
imageFile = Image.FromFile(dlg.FileName);
imgHeight = imageFile.Height;
if (imgHeight > 350)
{
MessageBox.Show("Not 350x350 Image", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
imgPhoto.Image = null;
}
else
{
PictureBox1.Image = new Bitmap(dlg.OpenFile());
}
}
dlg.Dispose();
}
Hope this will help.
Try this :
OpenFileDialog fileDialog = new OpenFileDialog
{
// managed GDI+ supports bmp, jpeg, gif, png and tiff.
Filter =
"Image files (*.bmp;*.jpg;*.gif;*.png;*.tiff)|*.bmp;*.jpg;*.gif;*.png;*.tiff|All files (*.*)|*.*",
};
if (fileDialog.ShowDialog() == DialogResult.OK)
{
// Many exceptions could be raised in the following code
try
{
var fileSize = new FileInfo(fileDialog.FileName);
var validFilesize = fileSize.Length <= 1024 * 100; // 100 kilo bytes
var validDimensions = false;
// free the file once we get the dimensions
using (Image image = Image.FromFile(fileDialog.FileName))
{
validDimensions = (image.Width <= 350) && (image.Height <= 350);
}
if (!validDimensions || !validFilesize)
{
MessageBox.Show("Error ! Choose another image");
}
else
{
// do something with the file here
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
In my main Form I have a method called SavePDFDocument():
private void SavePDFDocument()
{
PDFWrapper pdfWrapper = new PDFWrapper();
pdfWrapper.CreatePDF(horizontalPictureScroller1.GetPictures(), "pdfDocument.pdf");
}
As you can see, right now I'm manually typing in a name for the file. I'd like to ask the user to choose where to save it and what name to give it.
This is the CreatePDF() method I'm using above:
public void CreatePDF(List<System.Drawing.Image> images, string filename)
{
if (images.Count >= 1)
{
Document document = new Document(PageSize.LETTER);
try
{
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
// step 3: we open the document
document.Open();
foreach (var image in images)
{
iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
if (pic.Height > pic.Width)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 700 / pic.Height;
pic.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 540 / pic.Width;
pic.ScalePercent(percentage * 100);
}
pic.Border = iTextSharp.text.Rectangle.BOX;
pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
pic.BorderWidth = 3f;
document.Add(pic);
document.NewPage();
}
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
// step 5: we close the document
document.Close();
}
}
Any suggestions?
Did you take a look at SaveFileDialog?
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
I believe this page describes what you are looking for:
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
}
A useful link: How to: Save Files Using the SaveFileDialog Component