2017-09-07 2 views
0

안녕하세요 저는 현재 docx 파일을 결합한 코드를 작성하려고합니다. 이 파일에는 텍스트, 이미지, 표 또는 방정식이있을 수 있습니다. 이 코드는 이러한 객체를 복사하여 기본 docx에 추가하는 것을 목표로합니다. 복사 및 텍스트, 이미지 및 테이블 docx 모듈의 'add_picture'및 'add_paragraph'메서드를 사용하여 표 병합 할 수 있지만 단어 수식이 작업을 수행 할 수 없습니다. 나는 docx의 xml을 파고 거기에서 방정식 섹션을 복사하려고 노력하기로 결정했다. 방정식을 기본 문서에 추가 할 수 있지만 사진, 텍스트 및 표를 계속 추가하면이 방정식은 docx에 표시됩니다. 내 질문이 있습니다 : 이유는 나타나는 개체를 반복하여 표시하고 싶습니다. 입니다.은 방정식을 docx 끝에 넣지 않도록하는 방법입니다.방정식을 docx에서 다른 docx의 특정 위치로 복사하는 방법은 무엇입니까?

문서 = 문헌 ('basedoc.docx') 하위 문서

  • GET리스트
  • 를 추가 :

    1. 베이스 문서를 작성 : 여기

      코드의 일부 간략한
    2. 하위 문서 목록을 통해 루프를 시작합니다.
    3. 각 하위 문서에 대해 반복하고 다른 상위 및 하위 개체를 찾습니다. 이 웹 사이트에서이 함수를 발견했습니다. 'iter_block_items'(https://github.com/python-openxml/python-docx/issues/276) 문서 항목을 블록이라고합니다.
    4. I는 타입 스타일 분류 하위 문서의 각 블록 항목

      및 방정식이 존재하는지 여부 :

      경우 isinstance (블록 조제) 다른

      if "r:embed" in block._element.xml: 
      
          append content,style, and equation arrays, content being a drawing/image 
      
      elif "m:oMathPara" in block._element.xml: 
      
          append content,style, and equation arrays, content being an equation 
          equationXml.append(block._element.xml) 
      
      elif 'w:br w:type="page"' in block._element.xml: 
      
          append content,style, and equation arrays, content being a page break 
      
      else: 
      
          append content,style, and equation arrays), content being text 
      

      :

      append content,style, and equation arrays, content being a table 
      
    5. 나는 내용 배열을 통해 내용과 스타일 I 루프 내 배열을 가지고 있고 테이블, 그림, pagebreaks, 및 텍스트를 추가하면.

      def AddEquation(self,document,equationContent): 
          document.save('temp.docx') 
          z = zipfile.ZipFile('temp.docx') 
          tree=etree.parse(z.open('word/document.xml')) 
          nmspcDict = tree.getroot().iter().next().nsmap 
      
          for key in nmspcDict: 
           ET.register_namespace(key, nmspcDict[key]) 
          tree2=etree.ElementTree(etree.fromstring(equationContent)) 
          xmlRoot2=tree2.getroot() 
          xmlRoot=tree.getroot() 
          xmlRoot[1].append(xmlRoot2) #note that [1] had to be used bc [0] was a comment. need to see if general case or not 
      
      
          tree.write("document.xml",encoding="utf-8", xml_declaration=True, standalone="yes", pretty_print=True) 
      
          with UpdateableZipFile.UpdateableZipFile("temp.docx","a") as o: 
           o.write("document.xml","word/document.xml") 
      
          document = Document('temp.docx') 
          os.remove('document.xml') 
          z.close() 
          os.remove('temp.docx') 
          return document 
      
      :

      if equationXml[i]=='0': #the content is either an image, table, text, or page break 
           if "Table" in str(contentStyle[i]): 
             insert table and caption 
           else: 
            if "drawing" in content[i]: 
             insert image and caption 
      
            elif "pageBreak" in content[i]: 
             document.add_page_break() 
            else: 
             insert text 
          else:      #there is an equation present 
           document=EquationInsert.(document,equationXml[i]) 
      

    내 EquationInsert 파일은 기본적으로 내가 (UpdateableZipFile 빠르게 압축 파일에 파일을 업데이트 내가 온라인으로 볼 수있는 코드가) 내 문서 객체를 재 작성 'AddEquation'라는 기능이 있습니다

    이 코드는 방정식을 추가하지만 기본 코드가 하위 문서 항목을 통해 계속 반복되므로 방정식이 기본 문서의 끝 부분으로 푸시됩니다. 내가 방정식 함수를 삽입하고 그것에서 새 문서를 만드는 docx를 반환하려고했지만 아무것도하지 못했습니다. 방정식을 만드는 방법에 대한 조언을 누군가가 매우 감사하게 될 파일의 ​​끝 부분에 가지 않으면. 그렇지 않으면이 방정식을 이미지로 변환하는 방법을 살펴 보거나 docx에서 처리 할 수있는 것을 시도해야합니다. 나는 해결책/제안/의견에 열려 있습니다. 감사!

    답변

    0

    XML로 답을 찾을 수있을 것입니다. opc-diag을 사용하여 .docx "패키지"의 XML "부분"을 편리하게 탐색 할 수 있습니다.

    Word 문서의 단락과 표는 부분에 <w:body> 요소 아래의 하위 요소로 있습니다. <w:body>의 마지막 요소는 섹션 요소 (<w:sectPr> IIRC)입니다. 해당 요소 다음에 방정식을 추가하는 경우 새 단락과 테이블이 위의 위에 추가 될 때 sectPr 요소가 계속 추가되어 바닥에 계속 플로팅됩니다.

    가능한 한 짧은 테스트 문서로 작업하고 코드에서 생성 된 XML을 검사하여 Word에서 손으로 직접 만든 원하는 방식으로 비교합니다. 그렇게하면 코드에있는 모든 요소 시퀀싱 문제를 신속하게 지적해야합니다.