此代码将在打印预览中添加“保存工具提示”,并将图片框保存为PDF格式。
class SavePrint : System.Windows.Forms.PrintPreviewDialog
{
public SavePrint()
: base()
{
if (this.Controls.ContainsKey("toolstrip1"))
{
ToolStrip tStrip1 = (ToolStrip)this.Controls["toolstrip1"];
ToolStripButton button1 = new ToolStripButton();
button1.Text = "Save";
button1.Click += new EventHandler(SaveDocument);
button1.Visible = true;
tStrip1.Items.Add(button1);
}
}
public void SaveDocument(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Save As PDF";
sfd.Filter = "PDF|*.pdf";
sfd.InitialDirectory = @"Desktop";
if (sfd.ShowDialog() == DialogResult.OK)
{
Bitmap bmp = new Bitmap(pictureBox.Image);//GETTING THE ERROR HERE
Graphics gr = Graphics.FromImage(bmp);
PdfDocument doc = new PdfDocument();
doc.Pages.Add(new PdfPage());
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
xgr.DrawImage(bmp, 0, 0);
doc.Save(sfd.FileName);
doc.Close();
}
}
}
我在这一行得到错误“Bitmap bmp = new Bitmap(pictureBox.Image)”我应该怎么做才能继承我的pictureBox?
答案 0 :(得分:1)
更改班级SavePrint
的构造函数以获得以下签名:
class SavePrint : System.Windows.Forms.PrintPreviewDialog
{
readonly Form1 parent;
public SavePrint(Form1 parent)
: base()
{
this.parent = parent;
// Remainder as before
}
}
然后在构造SavePrint
时,将适当的实例Form1
传递给构造函数。
SavePrint savePrint = new SavePrint(this);
完成后,您的SavePrint
将能够访问其字段和属性:
Bitmap bmp = new Bitmap(parent.pictureBox.Image);
顺便说一句,你应该将所有disposables包装在using
语句中,如下所示:
using (Bitmap bmp = new Bitmap(parent.pictureBox.Image))
using (Graphics gr = Graphics.FromImage(bmp))
{
}