Source

paradocx / paradocx / package.py

from openpack.basepack import ContentType, Part, Relationship
from openpack.officepack import OfficePackage

# these modules must be imported for their Parts to be properly recognized
import document
import numbering
import styles
import headerfooter

class WordPackage(OfficePackage):
	def __init__(self):
		"""
		Construct a WordPackage.
		"""
		super(WordPackage, self).__init__()
		self.quickstart()

	def _load(self, *args, **kwargs):
		# re-initialize this package without the quickstart
		super(WordPackage, self).__init__()
		super(WordPackage, self)._load(*args, **kwargs)

	def quickstart(self):
		self.content_types.add(
			ContentType.Default(
				"application/xml",
				"xml",
			)
		)
		self.content_types.add(
			ContentType.Default(
				"application/vnd.openxmlformats-package.relationships+xml",
				"rels",
			)
		)
		start = document.DocumentPart(self, '/word/document.xml')
		self.content_types.add(
			ContentType.Override(
				start.content_type,
				start.name,
			)
		)
		self[start.name] = start
		self.relate(start)

if __name__ == '__main__':
	import sys
	from textwrap import dedent
	from this import s as zen_encoded
	from openpack.basepack import Relationships, CoreProperties
	
	trun = """\
	<w:p>
	  <w:r>
		<w:t>%s</w:t>
	  </w:r>
	</w:p>
"""
	raw_zen = zen_encoded.decode('rot13')
	zen = "".join(trun % line for line in raw_zen.splitlines())

	body = dedent("""
		<?xml version="1.0" encoding="utf-8"?>
		<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
		  <w:body>
			<w:p>
			  <w:r><w:t>Generated by:</w:t></w:r>
			</w:p>
			<w:p>
			  <w:r><w:t>Python %s</w:t></w:r>
			</w:p>
		%s
		  </w:body>
		</w:document>
		""").lstrip() % (sys.version, zen)
	op = WordPackage()
	op.start_part.data = body.decode('utf-8')
	op.core_properties = cp = CoreProperties(op, '/docProps/core.xml')
	cp.encoding = 'utf-8'
	op[cp.name] = cp
	op.content_types.add_override(cp)
	op.relate(cp)
	cp.creator = "Testy McTest"
	op.save('test.docx')