c# - 如何获取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 MissingValue,
ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref oVisible, ref oOpenAndRepair, ref MissingValue,
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 MissingValue, ref oRange, ref MissingValue, ref oFrom, ref oTo, ref oItem, ref oCopies, ref MissingValue,
ref oPageType, ref oPrintToFile, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
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 beginning 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;
}
推荐阅读
- biopython - 如何使用 biopython 查询 fasta 文件中的区域?
- couchdb - couchdb 复制一个方向不能连续工作
- php - 使用 CodeIgniter 4 从数据库中列出用户
- javascript - 在 mapboxgl 标记弹出窗口中添加一个可点击的 div
- python - 格式化为嵌套字典
- r - 将 DF 中的值相加并创建一个新值
- typeerror - ReactJS:this.props.AddContact 不是一个函数
- c# - 为什么比较两个字符串时会提取额外的单词
- javascript - 我有一个数组中的数据,并希望删除其中的一部分
- python - 在 Python 中用 2 个点和 2 个角度画一条线(它是一个变形的梁)