locked
Print specified area of excel as PDF RRS feed

  • Question


  • Any solution to print a specific area of excel as a PDF files?Thank you. Can anyone offer an example?

    Wednesday, April 8, 2015 2:43 AM

Answers

  • If what you need is to make that area printed as pdf,you can  convert that area as a PDF page and then print the PDF page,  although I don't know that make any sense.

    Recommend an Excel tool for u,  download this two .dll,(link1,link2) files and add reference to your project, then refer the following code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Spire.Pdf;
    using Spire.Xls;
    using System.Drawing;
    using System.Windows.Forms;
    using Spire.Pdf.Annotations;
    using Spire.Pdf.Widget;
    using System.Drawing.Printing;
    
    
    namespace Excel_to_PDF_print
    {
        class Program
        {
            static void Main(string[] args)
            {
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("test.xlsx", ExcelVersion.Version2010);
                //Get the first sheet and add a new sheet to store your area.
                Worksheet sheet = workbook.Worksheets[0];
                workbook.Worksheets.Add("Newsheet");
                workbook.SaveToFile("result.xls");
                //Copy your area to new sheet.
                workbook.Worksheets[0].Range["A1:G10"].Copy(workbook.Worksheets[1].Range["A7:D11"]);
               //convert new sheet to pdf
                workbook.Worksheets[1].SaveToPdf("result.pdf", Spire.Xls.FileFormat.PDF);
                // Save and preview PDF
              
                //Print PDF
               PdfDocument doc = new PdfDocument();
               doc.LoadFromFile("result.pdf");
    
               //Use the default printer to print all the pages
              
               //Set the printer and select the pages you want to print
    
               PrintDialog dialogPrint = new PrintDialog();
               dialogPrint.AllowPrintToFile = true;
               dialogPrint.AllowSomePages = true;
               dialogPrint.PrinterSettings.MinimumPage = 1;
               dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
               dialogPrint.PrinterSettings.FromPage = 1;
               dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;
    
               if (dialogPrint.ShowDialog() == DialogResult.OK)
               {
                   doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
                   doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
                   doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;
    
                   PrintDocument printDoc = doc.PrintDocument;
                   dialogPrint.Document = printDoc;
                   printDoc.Print();
               }
    
    
    
    
            }
        }
    }

    • Proposed as answer by Kristin Xie Thursday, April 9, 2015 2:17 AM
    • Marked as answer by Kristin Xie Wednesday, April 22, 2015 10:46 AM
    Wednesday, April 8, 2015 2:49 AM
  • Hi,

    There are number of ways to achieve this.

    1) You can use Office 2007/2010's built-in export functionality to accomplish this.

    The method you need to call is Workbook.ExportAsFixedFormat()

    public bool ExportWorkbookToPdf(string workbookPath, string outputPath)
    {
        // If either required string is null or empty, stop and bail out
        if (string.IsNullOrEmpty(workbookPath) || string.IsNullOrEmpty(outputPath))
        {
            return false;
        }
    
        // Create COM Objects
        Microsoft.Office.Interop.Excel.Application excelApplication;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook;
    
        // Create new instance of Excel
        excelApplication = new Microsoft.Office.Interop.Excel.Application();
    
        // Make the process invisible to the user
        excelApplication.ScreenUpdating = false;
    
        // Make the process silent
        excelApplication.DisplayAlerts = false;
    
        // Open the workbook that you wish to export to PDF
        excelWorkbook = excelApplication.Workbooks.Open(workbookPath);
    
        // If the workbook failed to open, stop, clean up, and bail out
        if (excelWorkbook == null)
        {
            excelApplication.Quit();
    
            excelApplication = null;
            excelWorkbook = null;
    
            return false;
        }
    
        var exportSuccessful = true;
        try
        {
            // Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)
            excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);
        }
        catch (System.Exception ex)
        {
            // Mark the export as failed for the return value...
            exportSuccessful = false;
    
            // Do something with any exceptions here, if you wish...
            // MessageBox.Show...        
        }
        finally
        {
            // Close the workbook, quit the Excel, and clean up regardless of the results...
            excelWorkbook.Close();
            excelApplication.Quit();
    
            excelApplication = null;
            excelWorkbook = null;
        }
    
        // You can use the following method to automatically open the PDF after export if you wish
        // Make sure that the file actually exists first...
        if (System.IO.File.Exists(outputPath))
        {
            System.Diagnostics.Process.Start(outputPath);
        }
    
        return exportSuccessful;
    }

    You need to install Office plugin SaveAs PDF and XPS. You can download it from the Microsoft official website.<o:p></o:p>

    2) Use the third party tool specifically designed for convert Excel to PDF.

    Excel to PDF .Net

    ExpertXLS Excel Library for .NET

    3) Another solution is automating OpenOffice.

    Refer: XLS to PDF conversion inside .net

    Rachit


    Please mark as answer or vote as helpful if my reply does


    • Edited by Rachit Sikroria Wednesday, April 8, 2015 5:03 AM
    • Proposed as answer by Kristin Xie Thursday, April 9, 2015 2:17 AM
    • Marked as answer by Kristin Xie Wednesday, April 22, 2015 10:46 AM
    Wednesday, April 8, 2015 5:02 AM

All replies

  • If what you need is to make that area printed as pdf,you can  convert that area as a PDF page and then print the PDF page,  although I don't know that make any sense.

    Recommend an Excel tool for u,  download this two .dll,(link1,link2) files and add reference to your project, then refer the following code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Spire.Pdf;
    using Spire.Xls;
    using System.Drawing;
    using System.Windows.Forms;
    using Spire.Pdf.Annotations;
    using Spire.Pdf.Widget;
    using System.Drawing.Printing;
    
    
    namespace Excel_to_PDF_print
    {
        class Program
        {
            static void Main(string[] args)
            {
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("test.xlsx", ExcelVersion.Version2010);
                //Get the first sheet and add a new sheet to store your area.
                Worksheet sheet = workbook.Worksheets[0];
                workbook.Worksheets.Add("Newsheet");
                workbook.SaveToFile("result.xls");
                //Copy your area to new sheet.
                workbook.Worksheets[0].Range["A1:G10"].Copy(workbook.Worksheets[1].Range["A7:D11"]);
               //convert new sheet to pdf
                workbook.Worksheets[1].SaveToPdf("result.pdf", Spire.Xls.FileFormat.PDF);
                // Save and preview PDF
              
                //Print PDF
               PdfDocument doc = new PdfDocument();
               doc.LoadFromFile("result.pdf");
    
               //Use the default printer to print all the pages
              
               //Set the printer and select the pages you want to print
    
               PrintDialog dialogPrint = new PrintDialog();
               dialogPrint.AllowPrintToFile = true;
               dialogPrint.AllowSomePages = true;
               dialogPrint.PrinterSettings.MinimumPage = 1;
               dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
               dialogPrint.PrinterSettings.FromPage = 1;
               dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;
    
               if (dialogPrint.ShowDialog() == DialogResult.OK)
               {
                   doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
                   doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
                   doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;
    
                   PrintDocument printDoc = doc.PrintDocument;
                   dialogPrint.Document = printDoc;
                   printDoc.Print();
               }
    
    
    
    
            }
        }
    }

    • Proposed as answer by Kristin Xie Thursday, April 9, 2015 2:17 AM
    • Marked as answer by Kristin Xie Wednesday, April 22, 2015 10:46 AM
    Wednesday, April 8, 2015 2:49 AM
  • Hi,

    There are number of ways to achieve this.

    1) You can use Office 2007/2010's built-in export functionality to accomplish this.

    The method you need to call is Workbook.ExportAsFixedFormat()

    public bool ExportWorkbookToPdf(string workbookPath, string outputPath)
    {
        // If either required string is null or empty, stop and bail out
        if (string.IsNullOrEmpty(workbookPath) || string.IsNullOrEmpty(outputPath))
        {
            return false;
        }
    
        // Create COM Objects
        Microsoft.Office.Interop.Excel.Application excelApplication;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook;
    
        // Create new instance of Excel
        excelApplication = new Microsoft.Office.Interop.Excel.Application();
    
        // Make the process invisible to the user
        excelApplication.ScreenUpdating = false;
    
        // Make the process silent
        excelApplication.DisplayAlerts = false;
    
        // Open the workbook that you wish to export to PDF
        excelWorkbook = excelApplication.Workbooks.Open(workbookPath);
    
        // If the workbook failed to open, stop, clean up, and bail out
        if (excelWorkbook == null)
        {
            excelApplication.Quit();
    
            excelApplication = null;
            excelWorkbook = null;
    
            return false;
        }
    
        var exportSuccessful = true;
        try
        {
            // Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)
            excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);
        }
        catch (System.Exception ex)
        {
            // Mark the export as failed for the return value...
            exportSuccessful = false;
    
            // Do something with any exceptions here, if you wish...
            // MessageBox.Show...        
        }
        finally
        {
            // Close the workbook, quit the Excel, and clean up regardless of the results...
            excelWorkbook.Close();
            excelApplication.Quit();
    
            excelApplication = null;
            excelWorkbook = null;
        }
    
        // You can use the following method to automatically open the PDF after export if you wish
        // Make sure that the file actually exists first...
        if (System.IO.File.Exists(outputPath))
        {
            System.Diagnostics.Process.Start(outputPath);
        }
    
        return exportSuccessful;
    }

    You need to install Office plugin SaveAs PDF and XPS. You can download it from the Microsoft official website.<o:p></o:p>

    2) Use the third party tool specifically designed for convert Excel to PDF.

    Excel to PDF .Net

    ExpertXLS Excel Library for .NET

    3) Another solution is automating OpenOffice.

    Refer: XLS to PDF conversion inside .net

    Rachit


    Please mark as answer or vote as helpful if my reply does


    • Edited by Rachit Sikroria Wednesday, April 8, 2015 5:03 AM
    • Proposed as answer by Kristin Xie Thursday, April 9, 2015 2:17 AM
    • Marked as answer by Kristin Xie Wednesday, April 22, 2015 10:46 AM
    Wednesday, April 8, 2015 5:02 AM
  • This is the simplest approach that I found:

    // Load excel file.
    ExcelFile workbook = ExcelFile.Load("Sample.xlsx");
    // Get active worksheet.
    ExcelWorksheet worksheet = workbook.Worksheets.ActiveWorksheet;
    // Set desired print area.
    worksheet.NamedRanges.SetPrintArea(worksheet.Cells.GetSubrange("A1", "F10"));
    
    // Save PDF file.
    workbook.Save("Sample.pdf");
    // Or print file.
    workbook.Print();
    The code comes from this excel library for C#, if you need some alterations or modifications then refer to following article about converting excel into a PDF file with C# or in case you do want to print then see this printing excel files example in C#.

    Friday, March 25, 2016 9:16 AM