gpt4 book ai didi

c# - 将工作表名称作为书签将 Excel 转换为 PDF

转载 作者:行者123 更新时间:2023-12-04 21:45:00 27 4
gpt4 key购买 nike

我想将我的 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 中显示为书签。我怎样才能做到这一点?

最佳答案

目前,仅使用 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");
}

关于c# - 将工作表名称作为书签将 Excel 转换为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68318368/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com