将界面导出为pdf,其实是将界面保存为jpg图片之后再使用itextsharp.dll控件将jpg文件导出为pdf文件。
1.先定义一个获取需要保存pdf的路径的函数
public static string GetExportPDFPath()
{
string filename = System.DateTime.Now.ToString().Replace("/" , "").Replace(":" , "")+"XXX";
var exportFileName = filename + ".pdf";
var saveFileDialog = new SaveFileDialog { FileName = exportFileName };
saveFileDialog.Filter = "导出数据文件(*.pdf)|*.pdf";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "导出数据文件";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
return saveFileDialog.FileName;
}
else
{
return String.Empty;
}
}
2.定义jpg文件转pdf的函数
public void ConvertJPGToPDF(string jpgfile, string pdf)
{
iTextSharp.text.Rectangle PageSize = new iTextSharp.text.Rectangle(this.Width, this.Height);
var document = new iTextSharp.text.Document(PageSize, 25, 25, 25, 25);
//var document = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(), 25, 25, 25, 25);
using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfWriter.GetInstance(document, stream);
document.Open();
using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var image = iTextSharp.text.Image.GetInstance(imageStream);
if (image.Height > PageSize.Height - 25)
{
image.ScaleToFit(PageSize.Width - 25, PageSize.Height - 25);
}
else if (image.Width > PageSize.Width - 25)
{
image.ScaleToFit(PageSize.Width - 25, PageSize.Height - 25);
}
image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
document.Add(image);
}
document.Close();
}
}
3.使用上述两个函数导出pdf
private void btnExport_Click(object sender, EventArgs e)
{
//GDI+
this.groupBox1.Visible = false;
this.label1.Focus();
//MessageBoxHelper.ShowInformationMsg(this.label3.Visible.ToString());
Bitmap bmp = new Bitmap(this.Size.Width, this.Size.Height);
this.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, Width, Height));
bmp.Save(".//temp.jpg");
//选择导出pdf的路径并导出 ITextSharp.dll插件
string pdfpath = GetExportPDFPath();
if (pdfpath == String.Empty)
{
MessageBoxHelper.ShowWarningMsg("导出失败,请重试!!");
this.groupBox1.Visible = true;
return;
}
else
{
ConvertJPGToPDF(".//temp.jpg", pdfpath);
MessageBoxHelper.ShowSuccessMsg("导出成功!!");
this.Close();
}
}
注:MessageBoxHelper为框架自带的类,与MesageBox的功能类似。