如何使用 XLWings 将 excel 文件缩小到单页打印?

问题描述 投票:0回答:1

我有一个 excel 文件,在执行“打印为 pdf”时,它不能完全适合单个页面。

这是一份常规报告,其中的行数因报告而异,因此最好以编程方式调整大小。

有没有办法在导出为 pdf 时“缩小”excel 以适合单个页面?

我正在使用 XLWings,但我对其他解决方案持开放态度。

excel xlwings
1个回答
0
投票

你没有说你是如何打印的,但这样的事情可能会有所帮助;
此代码示例有几个页面设置选项。

  1. 如果需要使用特定范围或最大行设置打印区域
  2. 使用 Zoom 将缩放设置为百分比
  3. 使用适合页面

您可以打印到“Microsoft Print to PDF”之类的打印队列或使用 Xlwings“to_pdf”。
如果 wb 只是打开并打印(未保存),这些设置都不会是永久性的。

import xlwings as xw


xlPrintErrorsDisplayed = 0
xlPrintNoComments = -4142
xlPortrait = 1
xlPaperA4 = 9
xlAutomatic = -4105
xlDownThenOver = 1

excelfile = 'foo.xlsx'
with xw.App(visible=False) as app:
    wb = xw.Book(excelfile)
    ws = wb.sheets('Sheet1')

    mr = ws.range('A' + str(wb.sheets[0].cells.last_cell.row)).end('up').row

    ### Setup a Print Area if required
    # ws.page_setup.print_area = '$A$1:$I$60'
    # ws.page_setup.print_area = f'$A$1:$L${mr}'

    ### Set PageSetup object
    ws_ps = ws.api.PageSetup

    ### Set a scaling
    # ws_ps.Zoom = 25

    ### Fit to Page
    # ws_ps.FitToPagesWide = 1
    # ws_ps.FitToPagesTall = 1

    ### Other page setup options that may be useful, there are others
    ### Constants like 'xlPrintNoComments' are in the Xlwings constants file, 
    ### I've just included the ones used in the example as hardcoded rather than importing for clarity.
    ws_ps.LeftMargin = 0.75
    ws_ps.RightMargin = 0.75
    ws_ps.TopMargin = 1
    ws_ps.BottomMargin = 1
    ws_ps.HeaderMargin = 0.5
    ws_ps.FooterMargin = 0.5
    ws_ps.PrintHeadings = False
    ws_ps.PrintGridlines = False
    ws_ps.PrintComments = xlPrintNoComments
    ws_ps.PrintQuality = 600
    ws_ps.CenterHorizontally = True
    ws_ps.CenterVertically = True
    ws_ps.Orientation = xlPortrait
    ws_ps.Draft = False
    ws_ps.PaperSize = xlPaperA4
    ws_ps.FirstPageNumber = xlAutomatic
    ws_ps.Order = xlDownThenOver
    ws_ps.BlackAndWhite = False
    ws_ps.PrintErrors = xlPrintErrorsDisplayed
    ws_ps.OddAndEvenPagesHeaderFooter = False
    ws_ps.DifferentFirstPageHeaderFooter = False
    ws_ps.ScaleWithDocHeaderFooter = True
    ws_ps.AlignMarginsHeaderFooter = True

    pdf_file = f"pdf1-2_{excelfile.replace('.', '_')}.pdf"

    ### Print to Print Queue 'Microsoft Print to PDF'
    ws.api.PrintOut(Copies=1, ActivePrinter='Microsoft Print to PDF')

    ### Use Xlwings print to pdf
    ws.to_pdf(path=pdf_file)
© www.soinside.com 2019 - 2024. All rights reserved.