[英]iTextSharp PDF rotating page is shifted
我尝试使用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.