簡體   English   中英

無法使用iTextSharp創建PDF文件

[英]Unable to create PDF file with 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. -是否需要已經創建文件或此處缺少某些內容?

這不是iTextSharp問題。 這是一個一般的I / O問題。 當嘗試使用路徑C:\\\\sample.pdf創建任何其他文件時,也會遇到相同的問題。 可能的原因是:不允許您直接寫入C:驅動器,或者文件sample.pdf已經存在並且不能被覆蓋(其權限不允許,或者例如,由於它在Windows中打開而被鎖定了) PDF查看器)。

您已經知道這一點,因為這正是錯誤消息所說的內容:

拒絕訪問路徑“ c:\\ sample.pdf”。

使用其他路徑。 用測試文件污染C:驅動器不是一個好習慣。

嘗試更改FileAccess

新的FileStream(“ c:\\ sample.pdf”,FileMode.Create,FileAccess.ReadWrite)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM