user123_456
user123_456

Reputation: 5805

Unable to create PDF file with iTextSharp

This is my code to create PDF file with iTextSharp library:

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();
        }

This line: PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c:\\sample.pdf", FileMode.Create)); is giving me this error Access to the path 'c:\sample.pdf' is denied. - do I need to have file already created or something is missing in here?

Upvotes: 0

Views: 4449

Answers (2)

Malhotra
Malhotra

Reputation: 439

try to change FileAccess

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

Upvotes: 2

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

This isn't an iTextSharp problem. It's a general I/O problem. You'll get the same problem when try to create any other file using the path C:\\sample.pdf. Possible reasons are: you're not allowed to write directly to the C: drive, or the file sample.pdf already exists and can't be overwritten (its permissions don't allow it, or it's locked for instance because it's opened in a PDF viewer).

You already knew this as that's exactly what the error message says:

Access to the path 'c:\sample.pdf' is denied.

Use a different path. It's not good practice to pollute the C: drive with test files.

Upvotes: 2

Related Questions