在iText和iTextSharp中,Document
对象是一个抽象的概念,可以自动处理各种间距、填充和边距。但不幸的是,这也意味着当您调用doc.Add()
时,它会考虑文档中现有的边距。(此外,如果您添加了其他任何内容,图像也将相对于该内容添加。)
一种解决方案是只需去除边距:
doc.SetMargins(0, 0, 0, 0);
相反,直接将图像添加到通过调用PdfWriter.GetInstance()
获得的PdfWriter
对象中更容易。您目前正在丢弃并未存储该对象,但您可以轻松更改行:
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog1.FileName,FileMode.Create));
然后您可以访问的DirectContent
属性,并调用其AddImage()
方法:
writer.DirectContent.AddImage(img)
在执行这个操作之前,您必须通过调用绝对定位来定位图片:
img.SetAbsolutePosition(0, 0)
以下是一个完整的工作中的C# 2010 WinForms应用程序,针对iTextSharp 5.1.1.0,显示了上面的
DirectContent
方法。它动态地创建了两个不同大小的图像,其中有两个红色箭头在垂直和水平方向上延伸。您的代码显然只需要使用标准的图像加载,因此可以省略很多内容,但我想提供一个完整的工作示例。有关更多详细信息,请参见代码中的注释。
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
string outputFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Images.pdf");
using (FileStream fs = new FileStream(outputFilename, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document()) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
using (Bitmap b1 = new Bitmap(100, 400)) {
using (Graphics g1 = Graphics.FromImage(b1)) {
using(Pen p1 = new Pen(Color.Red,10)){
p1.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
p1.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
g1.DrawLine(p1, 0, b1.Height / 2, b1.Width, b1.Height / 2);
g1.DrawLine(p1, b1.Width / 2, 0, b1.Width / 2, b1.Height);
iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(b1, BaseColor.WHITE);
img1.SetAbsolutePosition(0, 0);
doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, b1.Width, b1.Height, 0));
doc.NewPage();
writer.DirectContent.AddImage(img1);
}
}
}
using (Bitmap b2 = new Bitmap(4000, 1000)) {
using (Graphics g2 = Graphics.FromImage(b2)) {
using (Pen p2 = new Pen(Color.Red, 10)) {
p2.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
p2.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
g2.DrawLine(p2, 0, b2.Height / 2, b2.Width, b2.Height / 2);
g2.DrawLine(p2, b2.Width / 2, 0, b2.Width / 2, b2.Height);
iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(b2, BaseColor.WHITE);
img2.SetAbsolutePosition(0, 0);
doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, b2.Width, b2.Height, 0));
doc.NewPage();
writer.DirectContent.AddImage(img2);
}
}
}
doc.Close();
}
}
}
this.Close();
}
}
}