如何将Windows窗体另存为PDF?

时间:2019-05-29 08:46:00

标签: c# pdf

我想将Windows表单另存为pdf。因此,我试图在许多stackoverflow的答案中使用建议的解决方案。但是我有一个问题。当我打开生成的.pdf文档时,我看到了所有打开的页面的屏幕(例如,我看到了一个窗口窗体+一个网页(我使用了两个监视器)。

我已经尝试过这个:

Bitmap bmp = new Bitmap(panelExample.Width, panelExample.Height);
Graphics mg = Graphics.FromImage(bmp);
mg.CopyFromScreen(0, panelExample.Height, panelExample.Width, 0, panelExample.Size);
DirectoryInfo directoryScreen = Directory.CreateDirectory(@"\pdf\");
string pathImage = Path.Combine(directoryScreen.FullName, "screenshot.png");
bmp.Save(pathImage, ImageFormat.Png);
Document document = new Document();
document.SetMargins(1, 1, 1, 1);
string path = Path.Combine(directoryScreen.FullName, "test.pdf");
FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
PdfWriter.GetInstance(document, stream);
document.Open();
FileStream imageStream = new FileStream(pathImage, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Image image = Image.GetInstance(imageStream);
document.Add(image);
document.Close();
Process.Start(path);

我该如何解决?

编辑: 我已经尝试过了:

...
Bitmap bitmap = new Bitmap(Width, Height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(Location, new Point(0,0), Size);
Document document = new Document();
Image image = Image.GetInstance(bitmap, ImageFormat.Bmp);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
document.SetPageSize(new iTextSharp.text.Rectangle(Size.Width + document.LeftMargin + document.RightMargin, Size.Height + document.TopMargin + document.BottomMargin));
document.Open();
document.Add(image);
document.Close();
Process.Start(path);

但是.pdf文档中的屏幕截图仍然错误。因此,我有2个饼图和8个标签,并且要保存为.pdf文档。有没有一种方法可以仅将图表和标签保存在.pdf文档中?我现在解决的方法是筛选所有表单(包括按钮和图片框)。例如“将饼图另存为位图并将图像添加到pdf”之类的内容

已解决:

DirectoryInfo directory = Directory.CreateDirectory(@"\pdf\");
string path = Path.Combine(directory.FullName, "test.pdf");
Bitmap bitmap = new Bitmap(panelExample.ClientRectangle.Width, panelExample.ClientRectangle.Height);
panelExample.DrawToBitmap(bitmap, panelExample.ClientRectangle);
Document document = new Document();
Image image = Image.GetInstance(bitmap, ImageFormat.Bmp);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
document.SetPageSize(new iTextSharp.text.Rectangle(Size.Width + document.LeftMargin + document.RightMargin, Size.Height + document.TopMargin + document.BottomMargin));
document.Open();
document.Add(image);
document.Close();
Process.Start(path);

0 个答案:

没有答案