c#输出pdf
public static string GetExportPDFPath()
{
string filename ="评价报告";
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;
}
}
//将jpg转成pdf
public void ConvertJPGToPDF(string jpgfile, string pdf)
{
var imageStream1 = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var image1 = iTextSharp.text.Image.GetInstance(imageStream1);
iTextSharp.text.Rectangle PageSize = new iTextSharp.text.Rectangle(image1.Width, image1.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();
}
}
private void btnAnchorPoint1_Click(object sender, EventArgs e)
{
//控制scrollbar的value
this.panel1.VerticalScroll.Value = 0;//跳到头
this.panel1.PerformLayout();//更新layout
//设置铆钉选中
this.btnAnchorPoint2.Selected = false;
this.btnAnchorPoint1.Selected = true;
}
//pdf
private void btnPrint_Click(object sender, EventArgs e)
{
try
{
btnAnchorPoint1_Click(this, null);
int primaryHeight = panel1.Height;
int primaryWith = chart1.Width+150;
panel1.Dock = DockStyle.None;
panel1.Width = primaryWith;
panel1.Height = this.dataGridView2.Location.Y + this.dataGridView2.Height;
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, panel1.Width - 50, panel1.Height));
panel1.Dock = DockStyle.Fill;
panel1.Height = primaryHeight;
bmp.Save(".//temp.jpg");
string pdfpath = GetExportPDFPath();
if (pdfpath == String.Empty)
{
return;
}
else
{
ConvertJPGToPDF(".//temp.jpg", pdfpath);
MessageBox.Show("导出成功");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}