converting xlsx to pdf in csharp

Here's a sample code to convert a xlsx file to pdf using OpenXML and iTextSharp libraries in C#:

main.cs
using DocumentFormat.OpenXml.Packaging;
using iTextSharp.text;
using iTextSharp.text.pdf;

public void ConvertExcelToPDF(string filePath, string outputFolder)
{
    // Open the excel file using OpenXML
    using (SpreadsheetDocument doc = SpreadsheetDocument.Open(filePath, false))
    {
        // Get the workbookpart
        WorkbookPart workbookPart = doc.WorkbookPart;
        
        // Create a PDF document
        Document pdfDoc = new Document();
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(outputFolder + "output.pdf", FileMode.Create));
        pdfDoc.Open();
        
        // Loop through each sheet in the workbook
        foreach (Sheet sheet in workbookPart.Workbook.Sheets)
        {
            // Get the worksheetpart for the current sheet
            WorksheetPart worksheetPart = workbookPart.GetPartById(sheet.Id) as WorksheetPart;
            
            // Use iTextSharp to create a new page for this sheet
            pdfDoc.NewPage();
            PdfContentByte cb = writer.DirectContent;
            
            // Get the dimensions of the current sheet and create a new table
            var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
            var columns = sheetData.Descendants<Column>().Count();
            PdfPTable table = new PdfPTable(columns);
            
            // Loop through each row and cell
            foreach (Row row in sheetData.Elements<Row>())
            {
                foreach (Cell cell in row.Elements<Cell>())
                {
                    // Get the cell value and add it to the table
                    string value = cell.InnerText;
                    table.AddCell(value);
                }
            }
            
            // Add the table to the PDF page
            table.HeaderRows = 1;
            cb.SaveState();
            cb.SetLineWidth(0f);
            cb.MoveTo(0, pdfDoc.PageSize.Height - 50f);
            cb.LineTo(0, 50f);
            cb.LineTo(pdfDoc.PageSize.Width - 50f, 50f);
            cb.Stroke();
            cb.RestoreState();
            table.WriteSelectedRows(0, -1, 0, pdfDoc.PageSize.Height - 50f, cb);
        }
        
        // Close the PDF document
        pdfDoc.Close();
    }
}
2265 chars
60 lines

To use this code, simply call the ConvertExcelToPDF method and pass in the path to the xlsx file, as well as an output folder to save the PDF file to:

main.cs
ConvertExcelToPDF("C:\\input.xlsx", "C:\\output\\");
53 chars
2 lines

Note that you'll need to add the iTextSharp NuGet package to your project in order to use the iTextSharp.text and iTextSharp.text.pdf namespaces.

gistlibby LogSnag