c# - 无法使用iTextSharp创建PDF文件

标签 c# pdf error-handling datatable itextsharp

这是我使用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.-我是否需要已经创建文件或此处缺少某些内容?

最佳答案

尝试更改 FileAccess

new FileStream("c:\sample.pdf", FileMode.Create, FileAccess.ReadWrite)

关于c# - 无法使用iTextSharp创建PDF文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17373481/

相关文章:

c# - 使用 SqlDataAdapter 更新数据库 View

c# - 不会为动态创建的复选框调用事件处理程序

pdf - 服务器静态 pdf - Vue CLI - Webpack - 问题

java - 如何在 xhtmlrenderer(飞碟)R8 中使用 CSS3 孤儿和寡妇属性?

python - 使用 Python 脚本从 FTP 下载 .pdf 文件

error-handling - 错误会停止制作程序吗?

c# - 如何使 Windows 8 Metro 滚动查看器响应鼠标滚轮?

haskell - 定义 MonadEither 类型类

.net - 调试Windows服务,添加数据库日志记录catch子句是个坏主意?

c# - 保留 FileUpload 控制值