使用.NET中的iTextSharp在特定页面上绘制pdf格式的水平/垂直线



我试图在一个特定的页码上用pdf绘制一条水平/垂直线(比如在8页中的第3页(。但是,我只能在第一页和最后一页画一条线。

这是我的代码:

步骤1:

public ActionResult CreatePDF(string id)
{
// Create the iTextSharp document.
Document doc = new Document();
// Set the document to write to memory.
MemoryStream memStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
writer.CloseStream = false;
doc.Open();

DrawThickLine(writer, 36f, 519f, 806f, 519f);//Horizontal Line

DrawThickLine(writer, 36f, 280f, 36f, 521f);//Vertical Line

// Close and get the resulted binary data.
doc.Close();

// Send the binary data to the browser.          
return BinaryContentData(memStream, "", "", d1.formnumber.Value);//External Binary Content method
}

步骤2:

private static void DrawThickLine(PdfWriter writer, float x1, float y1, float x2, float y2)
{
PdfContentByte contentByte = writer.DirectContent;
contentByte.SetLineWidth(4.0f);   // Make a bit thicker than 1.0 default
contentByte.SetColorStroke(Color.BLACK);
contentByte.MoveTo(x1, y1);
contentByte.LineTo(x2, y2);
contentByte.Stroke();
}

任何帮助都将不胜感激!!

工作一个小时后,以下是我的解决方案。

步骤1:

public ActionResult CreatePDF(string id)
{
// Create the iTextSharp document.
Document doc = new Document();
// Set the document to write to memory.
MemoryStream memStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
writer.CloseStream = false;
doc.Open();

// DrawThickLine(writer, 36f, 519f, 806f, 519f);//Horizontal Line
// DrawThickLine(writer, 36f, 280f, 36f, 521f);//Vertical Line
// Close and get the resulted binary data.
doc.Close();

// Send the binary data to the browser.          
return BinaryContentData(memStream, "", "", id);//External Binary Content method
}

步骤2:

protected ActionResult BinaryContentData(MemoryStream pdf, string UserPwd, string OwnerPwd, string uid)
{
PdfReader reader = new PdfReader(pdf);
MemoryStream output = new MemoryStream();
PdfStamper pdfStamper = new PdfStamper(reader, output);
pdfStamper.Writer.CloseStream = false;

for (int pageIndex = 1; pageIndex <= reader.NumberOfPages; pageIndex++)
{
if (pageIndex == 3)//Page 3
{
DrawThickLine(pdfStamper, pageIndex, 36f, 519f, 806f, 519f);//Horizontal Line
DrawThickLine(pdfStamper, pageIndex, 36f, 280f, 36f, 521f);//Vertical Line
}
}
............//some code goes here
return new BinaryContentResult(buffer, "application/pdf", uid);
}

步骤3:

private static void DrawThickLine(PdfStamper pdfStamper, int pageIndex, float x1, float y1, float x2, float y2)
{
PdfContentByte cb = pdfStamper.GetOverContent(pageIndex);
cb.SetLineWidth(4.0f);   // Make a bit thicker than 1.0 default
cb.SetColorStroke(Color.BLACK);
cb.MoveTo(x1, y1);
cb.LineTo(x2, y2);
cb.Stroke();
}

最新更新