使用pythondocx获取MS-Word段落的起始页(和结束页)

2024-09-29 23:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在自动创建一个msword文档。当它完成后,我需要能够将它保存为PDF,并在Word文档的PDF版本中插入一些其他/外部PDF页面。为此,我计划在Word文档中留下标记(例如“[pdfgoesher]”)在自己的页面上。在

要插入/替换新的PDF页面,我需要知道标记在哪些页面上。PythonDocx有办法确定一个段落开始(和结束)的页码吗?我已经通读了python-docx documentation,但似乎没有任何与此相关的内容。我知道我可以循环浏览所有段落并找到我感兴趣的段落,但我找不到确定的方法来获取段落的页码。在

有没有我忽略的方法?如果没有,对于如何完成插入PDF页面的主要目标,还有其他建议吗?在


Tags: 方法文档标记版本pdf页面计划word
2条回答

感谢@scanny的反馈。因为在python-docx中没有办法做到这一点,而且我还是要把文档转换成PDF格式,所以我决定在Word文档转换成PDF之后使用pdfminer来获取页码。这段代码可能很长,但它可以完成任务

import re
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO

def xmlToLines(xml):
    text = ''.join(xml)
    return text.split('\n')

#Convert a PDF found at the 'path' and turns it into XML lines
#path is the full path directory to the PDF file you're reading from 
def convert_pdf_to_xml(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = XMLConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = file(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    print 'Converting following file from PDF to XML: \n - ' + str(path)
    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    text = retstr.getvalue()
    lines = xmlToLines(text)

    #Close out pdf and I/O's
    fp.close()
    device.close()
    retstr.close()

    return lines

#returns a list of every page number where the field marker is found in the PDF
def getPagesWithField(wordPdfPath, field):
    lines = convert_pdf_to_xml(wordPdfPath)
    page_regex = r'page id="[0-9]*"'
    t_regex = r'<text font='
    pagesFound = []
    text = ''
    field = field.replace('<','&').replace('>','&')
    for i in range(len(lines)):
        #If it's a new page line, increment to the new page
        if len(re.findall(page_regex, lines[i])) > 0:
            page = int(re.findall(r'[0-9]{1,}', lines[i])[0])
            #print 'page: ' + str(page)
        #If it's the end of a line
        elif lines[i] == '<text>':
            #print "Text: " + text
            #check if the collected text is the field you're looking for 
            if field in text:
                pagesFound.append(page)
            text = ''
        #If it's a line with a text character, add it to text
        elif len(re.findall(t_regex, lines[i])) > 0:
            text = str(text + re.findall(r'>[^\r\n]*</text>',lines[i])[0][1])

    pagesFound = list(set(pagesFound))
    pagesFound.sort()       
    return pagesFound

在此之后,PyPDF2可用于简单的PDF页面插入/合并

简单的回答是否定的。页码是在呈现时确定的,并且由于可用字体等因素而依赖于设备。在

这个答案有更多的细节: Page number python-docx

相关问题 更多 >

    热门问题