无法使用iTextSharp创建PDF文件

本文关键字:创建 PDF 文件 iTextSharp | 更新日期: 2023-09-27 18:20:31

这是我用iTextSharp库创建PDF文件的代码:

public void ExportToPdf(DataTable dt)
        {
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c:''sample.pdf", FileMode.Create));
            document.Open();
            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);
            PdfPTable table = new PdfPTable(dt.Columns.Count);
            PdfPRow row = null;
            float[] widths = new float[] { 4f, 4f, 4f, 4f };
            table.SetWidths(widths);
            table.WidthPercentage = 100;
            int iCol = 0;
            string colname = "";
            PdfPCell cell = new PdfPCell(new Phrase("Products"));
            cell.Colspan = dt.Columns.Count;
            foreach (DataColumn c in dt.Columns)
            {
                table.AddCell(new Phrase(c.ColumnName, font5));
            }
            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    table.AddCell(new Phrase(r[0].ToString(), font5));
                    table.AddCell(new Phrase(r[1].ToString(), font5));
                    table.AddCell(new Phrase(r[2].ToString(), font5));
                    table.AddCell(new Phrase(r[3].ToString(), font5));
                }
            } document.Add(table);
            document.Close();
        }

这一行:PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c:''sample.pdf", FileMode.Create));给了我这个错误Access to the path 'c:'sample.pdf' is denied.-我需要已经创建文件还是这里缺少什么?

无法使用iTextSharp创建PDF文件

尝试更改FileAccess

新FileStream("c:''sample.pdf",FileMode.Create,FileAccess.ReadWrite)

这不是iTextSharp的问题。这是一个常见的I/O问题。当尝试使用路径C:''sample.pdf创建任何其他文件时,也会遇到同样的问题。可能的原因是:您不允许直接写入C:驱动器,或者文件sample.pdf已经存在,无法覆盖(其权限不允许,或者因为在PDF查看器中打开而被锁定)。

你已经知道了,因为这正是错误消息所说的:

拒绝访问路径"c:''sample.pdf"。

请使用其他路径。用测试文件污染C:驱动器是不好的做法。