非常感谢aspose团队,经过前期的开发,目前在线生成word并自动转换成pdf,并成功上线,反响不错!
现在有一个问题,当word模板与数据merge后,生成的word文档有2页,并且第2页的内容只占用了一点点,如果这样转换为pdf也是2页,非常浪费纸张并且不环保。
请问在这样的情况下,能否用代码来判断:
- 生成后的word一共有几页?
2.最后一页的的内容占用了纸张的高度?
如果能够得到这个高度,我们就可以用代码将页面的pagesize调整到一页的高度。最后再生成pdf就是一页了。
或者对此问题有没更好的解决办法??
期待您的解答。谢谢!
@hzjianglf,
您可以使用以下代码获取段落在页面中结束的位置:
Document doc = new Document("E:\\temp\\in.docx");
LayoutCollector layoutCollector = new LayoutCollector(doc);
LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
{
layoutEnumerator.Current = layoutCollector.GetEntity(para);
Console.WriteLine("Page: {0}, Bottom in inches: {1}", layoutCollector.GetEndPageIndex(para), layoutEnumerator.Rectangle.Bottom / 72);
}
之后你可以减少Paragraphs中文本的大小,如下所示:
foreach(Run run in doc.FirstSection.Body.LastParagraph)
{
run.Font.Size = 8;
}
要获取Document中的总页数,请使用以下代码:
Console.WriteLine(doc.PageCount);
希望这可以帮助。
@awais.hafeez
非常感谢! 通过论坛历史贴子的学习和参考您的代码,用以下代码获取了最后一页的位置:
LayoutCollector collector = new LayoutCollector(doc);
LayoutEnumerator enumerator = new LayoutEnumerator(doc);
enumerator.setCurrent(collector.getEntity(doc.getLastSection().getBody().getLastParagraph()));
double lasty= enumerator.getRectangle().getY();
请问:
- 如何不遍历节点,能否直接取得第一页的最后一个Paragraph的位置?(假定doc有多页)
- 用enumerator.getRectangle().getY()取得的数值,与ms word 2010标尺上的数值还有略微的差异,请问这是正常的吗?
谢谢!
@awais.hafeez
延续以上的问题, 请问aspose Word或者pdf 有没这个功能: 就是将一个自定义纸张大小的Word文档保存为A4纸张的pdf,如果可以这样,可以大大方便用户打印。
谢谢!
@hzjianglf,
MS Word文档中没有“页面”的概念,因此无法直接获取任何页面上的最后一个段落。 您需要遍历Paragraph集合并获取Paragraphs的页码才能确定最后一个Paragraph。
顺便说一句,您需要考虑顶部,左侧,右侧,底部边距才能获得节点的确切位置。
Document doc = new Document("E:\\temp\\in.docx");
// Suppose any Node
Paragraph anyPara = doc.LastSection.Body.LastParagraph;
// Get the Section of this Node
Section sec = (Section) anyPara.GetAncestor(NodeType.Section);
// Get PageSetup
PageSetup ps = sec.PageSetup;
Console.WriteLine(ps.TopMargin + " etc");
此外,您可以使用以下代码保存为A4纸张尺寸设置的PDF。
Document doc = new Document("E:\\temp\\in.docx");
foreach(Section sec in doc.Sections)
{
PageSetup ps = sec.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.A4;
}
doc.Save("E:\\Temp\\19.5.pdf");
希望这可以帮助。
@awais.hafeez
非常感谢你的解答。
可能我没有把问题表述清楚,我的需求是:
现在有一个word文档,这个文档的页面设置是21cm*40cm,我想输出 A4纸张大小的pdf文件,就像在word中打印成A4的pdf文件一样。(而不是把word的纸张大小修改成A4,这样的话,页数会改变了)
请问 aspose word或者pdf组件有这样的功能吗?
@hzjianglf,
请尝试使用以下代码:
Document doc = new Document("E:\\temp\\in.docx");
foreach (Section sec in doc.Sections)
{
PageSetup ps = sec.PageSetup;
// A4 is 8.27 by 11.69 inches
ps.PageWidth = 8.27 * 72; // multiply it with 2.54 to get value in Centimeters
ps.PageHeight = 11.69 * 72;
}
doc.Save("E:\\Temp\\19.5.pdf");