首页 > 解决方案 > 如何适合打印的固定文档?

问题描述

我目前正在使用 C# 语言和 .Net Framework 4.8 开发 WPF 应用程序在MainWindow我有Print菜单按钮来生成Fixed Document这样的

    private void clPrintMenu_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        e.Handled = true;

       /* Margins is a User-defined structure to set Top, Right, Bottom and Left values
          in Cm, Inches and Pixels */
        Margins margins = new Margins(21, 29.7);
        margins.Unit = Units.Pixel;
        Size sz = new Size(margins.Left.Value, margins.Top.Value);

        FixedDocument document = new FixedDocument();
        document.DocumentPaginator.PageSize = sz;

        /* CashJournal is a UserControl designed as an A4 sheet the list below contains several
           Cashjournal which represent multiple pages */
        List<CashJournal> journals = CashJournal.PrintJournals;
        foreach (CashJournal jrl in journals)
        {
            FixedPage page = new FixedPage();
            page.Width = margins.Left.Value;
            page.Height = margins.Top.Value;

            FixedPage.SetLeft(jrl, 0);
            FixedPage.SetTop(jrl, -20);
            page.Children.Add(jrl);

            PageContent content = new PageContent();
            ((IAddChild)content).AddChild(page);

            document.Pages.Add(content);
        }

        /* The document is then passed to a window for preview */
        CashPrintPreview dialog = new CashPrintPreview(selectedTab, document);
        dialog.ShowDialog();
    }

在 CashPrintPreview 中,文档显示在一个DocumentViewer有一个Print按钮的地方。我修改了Print() CommandBinding将函数绑定到我的自定义函数PrintPreview

    private void PrintView(object sender, ExecutedRoutedEventArgs e)
    {
        PrintDialog dialog = new PrintDialog();
        bool? rslt = dialog.ShowDialog();
        if (rslt != true)
            return;

        /* This block is my problem */
        PrintQueue queue = dialog.PrintQueue;
        PrintCapabilities capabilities = queue.GetPrintCapabilities();
        Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
        document.DocumentPaginator.PageSize = sz;
        XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(queue);
        writer.Write(document);
    }

当我从 中选择 时XPS printerPrintDialog创建的文件会完美呈现在预览中。但是当我PDF printer从 Adob​​e 中选择时,文档的缩放比例不好,比如顶部的边距太多而左边的边距不够。

我该如何解决这个问题。谢谢。PS。请明确。

标签: c#wpf.net-framework-4.8

解决方案


我终于可以FixedDocument使用 Acrobat 打印机打印 PDF 文件了。我只需要将 my 传递documentPrintDocument所选打印机的功能:

private void PrintView(object sender, ExecutedRoutedEventArgs e)
{
  PrintDialog dialog = new PrintDialog();
  
  bool? rslt = dialog.ShowDialog();
  if (rslt != true)
    return;

  dialog.PrintDocument(((IDocumentPaginatorSource)document).DocumentPaginator, "");
}

推荐阅读