如何解决如何获取word文档的起始页码?
我只想将 Word 文档的前 10 页打印为 PDF/TIFF 图像。我能够使用以下代码打印 word 文档。
Microsoft.Office.Interop.Word.Application WordApp = null;
Microsoft.Office.Interop.Word.Documents WordDocs = null;
Microsoft.Office.Interop.Word.Document WordDoc = null;
WordApp = new Microsoft.Office.Interop.Word.Application();
WordDocs = WordApp.Documents;
object MissingValue = System.Reflection.Missing.Value;
object fileName = @"file path here",oConfirmConversions = false,oReadOnly = true,oAddToRecentFiles = false,oRevert = true,oVisible = true,oOpenAndRepair = true,oNoEncodingDialog = true;
try
{
WordDoc = WordDocs.OpenNoRepairDialog(ref fileName,ref oConfirmConversions,ref oReadOnly,ref oAddToRecentFiles,ref MissingValue,ref oVisible,ref oOpenAndRepair,ref oNoEncodingDialog,ref MissingValue);
object oBackground = false,oRange = WdPrintOutRange.wdPrintFromTo,oFrom = "1",oTo = "10",oCopies = 1,oPageType = 0,oPrintToFile = false,oItem = 0;
WordDoc.PrintOut(ref oBackground,ref oRange,ref oFrom,ref oTo,ref oItem,ref oCopies,ref oPageType,ref oPrintToFile,ref MissingValue);
}
catch (COMException e)
{
}
finally
{
try
{
if (WordDoc != null)
Marshal.FinalReleaseComObject(WordDoc);
if (WordDocs != null)
Marshal.FinalReleaseComObject(WordDocs);
if (WordApp != null)
Marshal.FinalReleaseComObject(WordApp);
}
catch { }
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
但是,当我在起始页不是 1 的 word 文档上进行测试时,却没有得到预期的结果。所以,我意识到我不应该打印从 1 开始的文档。相反,我需要使用起始页码。
那么,如何获取word文档的起始页码?
我真的很难查看此处提供的文档。 https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word
解决方法
我得到了我需要的答案。感谢帖子How to change the starting page number in word in microsoft interop? 起初,解决方案并不是很清楚,因为我希望获得部分的索引 0。但是发现索引是从1开始不是0。
工作代码
public int getStartingNumber(Document WordDoc)
{
var sections = WordDoc.Sections;
for (int i = 1; i <= sections.Count; i++)
{
var section = sections[i];
var headers = section.Headers;
foreach (HeaderFooter headerfooter in headers)
{
var pageNumbers = headerfooter.PageNumbers;
return pageNumbers.StartingNumber;
}
}
return -1;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。