将在iTextSharp.text.Document创建时设置的方向传播到Print对话框

本文关键字:传播 方向 Print 对话框 设置 text iTextSharp Document 创建 将在 | 更新日期: 2023-09-27 18:14:03

我使用iTextSharp创建一个横向PDF文档,通过使用PageSize. a4 . rotate ()来设置其PageSize。文档被输入到中,然后作为字节数组(在VARBINARY字段中)保存到数据库中。

Stream stream = new MemoryStream(); 
iTextSharp document = new Document();
document.SetPageSize(PageSize.A4.Rotate());
var writer = PdfWriter.GetInstance(document, stream)
document.Open()
// Write to the document
document.Close();
byte[] file = stream.ToArray();
/* In the actual environment the byte array is stored in the database, to be retrievable later */   
// WHERE context: HttpContext in a class that implements IHttpHandler
context.Response.AppendHeader("Content-Disposition", "attachment;filename=Test.pdf");
context.Response.AppendHeader("Content-Length", file.Length.ToString());
context.Response.ContentType = MediaTypeNames.Application.Pdf;
context.Response.BinaryWrite(file);

我遇到的问题是,当它通过浏览器检索和打开(或保存到磁盘)时,打印时,打印对话框以默认的纵向方向打开。

既然要让所有用户首先进入页面设置并将方向设置为横向并不是一件容易的事情,那么如何将文档创建时使用的方向设置一直传播到打印对话框呢?

将在iTextSharp.text.Document创建时设置的方向传播到Print对话框

您可以尝试将PdfWriter属性的PICKTRAYBYPDFSIZE属性设置为true。较新版本的adobeacrobat/Reader会检测到这一点,并自动勾选打印对话框上的"根据PDF页面大小选择纸张来源"复选框。不幸的是,这是一个"提示",并不是所有的PDF阅读器实现。

        string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Landscape.pdf");
        using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (Document doc = new Document(PageSize.LETTER.Rotate()))
            {
                using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
                {
                    writer.AddViewerPreference(PdfName.PICKTRAYBYPDFSIZE, PdfBoolean.PDFTRUE);
                    doc.Open();
                    doc.Add(new Paragraph("test"));
                    doc.Close();
                }
            }
        }

使用

var rect = new Rectangle(0, 0, PageSize.A4.Height, PageSize.A4.Width, 0);
var document = new Document(rect, 0, 0, 0, 0);