iTextSharp PDF旋转页面被移动
本文关键字:移动 PDF 旋转 iTextSharp | 更新日期: 2023-09-27 18:29:26
我尝试使用iTextSharp创建一个多页pdf文档。我有一个包含自身方向的对象(横向或纵向)。当第一个对象包含需要横向模式的信息时,我用Document doc = new Document(PageSize.A4.Rotate(), 10f, 10f, 10f, 0f)
创建文档。在下一个元素处于人像模式之前,这个效果非常好!如果一个元素处于纵向模式,我会再次设置页面大小:doc.SetPageSize(PageSize.A4);
。
此时,元素应该位于PDF文档中的纵向A4页面上,但它仍处于横向模式。它只切换页面,直到到达新对象或当前元素中的分页!
这是我的代码:
TableObject to_first = myTables.First();
//current object need landscape orientation
if (to_first._orientation == "landscape")
{
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
using (Document doc = new Document(PageSize.A4.Rotate(), 10f, 10f, 10f, 0f))
{
//Create a writer that's bound to our PDF abstraction and our stream
using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
//writer.CloseStream = false;
//loop all tableobjects inside the document & the instance of PDFWriter itself!
foreach (TableObject to in myTables.ToList())
{
doc.NewPage();
//look for the requested orientation by the current object and apply it
if (to._orientation == "landscape")
{
doc.SetPageSize(PageSize.A4.Rotate());
}
else if (to._orientation == "portrait")
{
doc.SetPageSize(PageSize.A4);
}
currentTable = to;
//Get the data from database corresponding to the current tableobject and fill all the stuff we need!
DataTable dt = getDTFromID(currentTable._tableID);
Object[] genObjects = new Object[5];
genObjects = gen.generateTable(dt, currentTable._tableName, currentTable._tableID.ToString(), currentTable, true);
StringBuilder sb = (StringBuilder)genObjects[1];
String tableName = sb.ToString();
Table myGenTable = (Table)genObjects[0];
String table = genObjects[2].ToString();
using (StringReader srHtml = new StringReader(table))
{
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
}
}
//After all of the PDF "stuff" above is done and closed but **before** we
//close the MemoryStream, grab all of the active bytes from the stream
doc.Close();
bytes = ms.ToArray();
}
}
}
如何确保每一页都正确旋转?
doc.SetPageSize
仅设置用于创建新页面的大小,而不设置用于现有页面的大小。因此,您应该移动
doc.NewPage();
在SetPageSize
调用之后调用:
//look for the requested orientation by the current object and apply it
if (to._orientation == "landscape")
{
doc.SetPageSize(PageSize.A4.Rotate());
}
else if (to._orientation == "portrait")
{
doc.SetPageSize(PageSize.A4);
}
// After setting the page size, trigger the generation of the new page
doc.NewPage();