使用itextsharp在pdf文件中绘制一条线的问题

我使用itextsharp在asp.net c#中生成pdf文件。 我无法绘制水平线/垂直线/虚线。

我尝试使用以下代码绘制一条线,我没有得到任何错误,但该行也没有显示在pdf文件中

PdfContentByte cb = wri.DirectContent; cb.SetLineWidth(2.0f); // Make a bit thicker than 1.0 default cb.MoveTo(20, pdfDocument.Top - 40f); cb.LineTo(400, pdfDocument.Top - 40f); cb.Stroke(); 

代码中有什么问题。是不是因为xy坐标的位置? 我曾使用粗略点来了解pdf中的大致位置,但该行在pdf文件中从不出现。

我期待的输出如下图所示。 在此处输入图像描述

您应该始终确保为您正在执行的操作设置颜色,否则您将不知道您将获得什么(它将来自之前执行的任何操作)。 尝试做cb.setStrokeColor(255,0,0)(纯红色),直到你想要它的行。

 Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1))); document.Add(p); 

iTextsharp线条画: –

 Dim line1 As New iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.Black, Element.ALIGN_LEFT, 1) pdfDoc.Add(New Chunk(line1)) 

你确定pdfDocument.Top正在返回一个值吗? 我使用了PageSize.Width and PageSize.Height

 iTextSharp.text.Document myDocument = new Document(PageSize.A4); PdfContentByte contentByte = writer.DirectContent; contentByte.SetLineWidth(1); contentByte.MoveTo(0, 14); contentByte.LineTo(myDocument.PageSize.Width,14); contentByte.Stroke(); 

你知道在iTextsharp中,坐标系统从左下角向上工作 – 你确定你的线路没有被拉到页面的下方吗?

我最后使用了plinth提供的答案以及上面提到的答案。 使用StringBuilder函数,您可以阻止事物然后手动绘制一条线,除非您有一个表格单元格占用TD标签的所有宽度以及一个单词。

 StringBuilder chistHeader = new StringBuilder(); StringBuilder chistCourses = new StringBuilder(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=CourseHistory.pdf"); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); Document pdfDoc = new Document(); PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream); pdfDoc.Open(); chistHeader = CourseHistoryHeader(Convert.ToInt32(hdUserID.Value), hdSystemPath.Value, "CourseHistory"); chistCourses = CourseHistoryCourses(Convert.ToInt32(hdUserID.Value), hdSystemPath.Value, "CourseHistory"); //write header for the pdf foreach (IElement element in HTMLWorker.ParseToList(new StringReader(chistHeader.ToString()), new StyleSheet())) { pdfDoc.Add(element); } //have to manually draw a line this way as ItextSharp doesn't allow a 
tag.... iTextSharp.text.pdf.draw.LineSeparator line1 = new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, BaseColor.BLACK, Element.ALIGN_LEFT, 1); pdfDoc.Add(new Chunk(line1)); //write out the list of courses foreach (IElement element in HTMLWorker.ParseToList(new StringReader(chistCourses.ToString()), new StyleSheet())) { pdfDoc.Add(element); } pdfDoc.Close(); HttpContext.Current.Response.Write(pdfDoc); HttpContext.Current.Response.End();
 Dim line1 As New iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.Black, Element.ALIGN_LEFT, 1) pdfDoc.Add(New Chunk(line1))