需要使用iTextSharp这个插件可以在nuget中安装
多个图片拼接成pdf文件的base64位数据
public static string ConvertPnl2ToPDFScreenBase64(/*Panel*/Panel[] pnl)
{
using (MemoryStream ms = new MemoryStream())
{
//Document对象:页面对象,就像是HTML里面的页面对象一样,用于操作页面内容和格式。通过Document对象的实例来操作内存中的pdf文件
Document doc = new Document(iTextSharp.text.PageSize.A4, 45, 25, 45, 25);
//PdfWriter对象:用于将Document对象写入PDF文件。
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
//------------------------------You need to actually write something to the document here...
doc.Open();
iTextSharp.text.Image image;
for (int i = 0; i < pnl.Length; i++)
{
Bitmap bitmap = new Bitmap(pnl[i].Width, pnl[i].Height);
pnl[i].DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, pnl[i].Width, pnl[i].Height));//关键步1
System.Drawing.Image img = bitmap;//转化为System.Drawing.Image
image = iTextSharp.text.Image.GetInstance(img, iTextSharp.text.Color.BLACK);//关键步2
//调整边距等格式
if (image.Height > iTextSharp.text.PageSize.A4.Height - 25)
{
//image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height);//测试一下边距!20190816
}
else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25)
{
//image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height);//测试一下边距!20190816
}
image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
doc.NewPage();//加这个是表示每个图片单独放一页,如果不加就是在一页里面累加
bool isSucess = doc.Add(image);//关键步3.
}
doc.Close();
var encodedPDF = Convert.ToBase64String(ms.ToArray());
return encodedPDF;
}
}
只导出单个控件:
Rectangle rect = new Rectangle(0, 0, panel1.Width, panel1.Height);
using (Bitmap bmp = new Bitmap(rect.Width, rect.Height))
{
this.panel1.DrawToBitmap(bmp, rect);
bmp.Save(@"D:\test.png");
}
导出整个窗体:
Bitmap bmp= new Bitmap(this.Width, this.Height);//实例化一个和窗体一样大的bitmap
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(this.Left, this.Top, 0, 0, new Size(this.Width, this.Height));//保存整个窗体为图片
bmp.Save(@"D:\test.png");
导出某个控件及该控件上所有的控件:
Bitmap bmp= new Bitmap(panel2.Width, panel2.Height);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(panel2.PointToScreen(Point.Empty), Point.Empty, panel2.Size);//只保存某个控件
bmp.Save(@"D:\test.png");