1

我想将我的 Excel 文件中的所有工作表保存为 PDF。目前,我为此使用 GemBox.Spreadsheet:

var workbook = ExcelFile.Load("file.xlsx");
var options = new PdfSaveOptions() { SelectionType = SelectionType.EntireFile };
workbook.Save("file.pdf", options);

现在我想让工作表名称(每个ExcelWorksheet.Name)在该输出 PDF 中显示为书签。我怎样才能做到这一点?

4

1 回答 1

3

目前,仅使用 GemBox.Spreadsheet 是不可能的,但您可以与 GemBox.Pdf 一起完成。

如果每个工作表都导出为单个页面,那么您可以这样做:

var workbook = ExcelFile.Load("input.xlsx");

// Set each worksheet to be exported as a single page.
foreach (var worksheet in workbook.Worksheets)
{
    worksheet.PrintOptions.FitWorksheetWidthToPages = 1;
    worksheet.PrintOptions.FitWorksheetHeightToPages = 1;
}

// Save the whole workbook as a PDF file.
var options = new GemBox.Spreadsheet.PdfSaveOptions();
options.SelectionType = SelectionType.EntireFile;
var stream = new MemoryStream();
workbook.Save(stream, options);

using (var document = PdfDocument.Load(stream))
{
    // Add bookmark (or outline) for each PDF page (or Excel sheet).
    for (int i = 0; i < document.Pages.Count; i++)
    {
        var page = document.Pages[i];
        var sheet = workbook.Worksheets[i];
        document.Outlines.AddLast(sheet.Name).SetDestination(page, PdfDestinationViewType.FitPage);
    }

    document.Save("output.pdf");
}

如果每个工作表都可以导出为多个页面,那么您可以这样做:

var workbook = ExcelFile.Load("input.xlsx");
var options = new GemBox.Spreadsheet.PdfSaveOptions();

using (var document = new PdfDocument())
{
    foreach (var worksheet in workbook.Worksheets)
    {
        // Save each worksheet as a PDF file.
        workbook.Worksheets.ActiveWorksheet = worksheet;
        var stream = new MemoryStream();
        workbook.Save(stream, options);

        using (var temp = PdfDocument.Load(stream))
        {
            // Copy PDF pages to destination PDF and add a bookmark.
            var firstPage = true;
            foreach (var tempPage in temp.Pages)
            {
                var page = document.Pages.AddClone(tempPage);
                if (firstPage)
                {
                    document.Outlines.AddLast(worksheet.Name).SetDestination(page, PdfDestinationViewType.FitPage);
                    firstPage = false;
                }
            }
        }
    }

    document.Save("output.pdf");
}
于 2021-07-12T05:40:30.707 回答