我尝试使用iTextSharp创建多页pdf文档。我有一个包含自身方向的对象(横向或纵向)。当第一个Object包含需要横向模式的信息时,我使用Document doc = new Document(PageSize.A4.Rotate(), 10f, 10f, 10f, 0f)
创建文档。这个工作非常好,直到下一个元素处于纵向模式!如果元素处于纵向模式,我再次设置pagesize: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();
}
}
}
如何确保每页都正确旋转?
答案 0 :(得分:2)
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();