How do I modify a document in a stream without changing the original document

Viewed 26

Following the tutorial provided by ASPOSE I am able to save a document to a stream:

# Read only access is enough for Aspose.words to load a document.
stream = io.FileIO(docs_base.my_dir + "Document.docx")

doc = aw.Document(stream)
# You can close the stream now, it is no longer needed because the document is in memory.
stream.close()

# ... do something with the document.

# Convert the document to a different format and save to stream.
dstStream =  io.FileIO(docs_base.my_dir + "Document.docx", "wb")
doc.save(dstStream, aw.SaveFormat.PDF)
dstStream.close()

However, when I do something with the document, the docx document is modified. How to do only save changes to the pdf output?

1 Answers

Aspose.Words does not modify the original document upon processing. The document is fully read into the memory, so the original file is not used by Aspose.Words after opening it. The DOCX file is modified in your case because you save the output document with the same file name as an input document, so the original document is replaced. You should modify your code like this:

# Read only access is enough for Aspose.words to load a document.
stream = io.FileIO(docs_base.my_dir + "Document.docx")

doc = aw.Document(stream)
# You can close the stream now, it is no longer needed because the document is in memory.
stream.close()

# ... do something with the document.

# Convert the document to a different format and save to stream.
dstStream =  io.FileIO(docs_base.my_dir + "Document.pdf", "wb")
doc.save(dstStream, aw.SaveFormat.PDF)
dstStream.close()

Or even simpler, if you work with files:

doc = aw.Document(docs_base.my_dir + "Document.docx")
# ... do something with the document.
doc.save(docs_base.my_dir + "Document.pdf")

Aspose.Words automatically detects the save format by the output file extension when you save to file.

Related