Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Last active November 3, 2020 15:17
Show Gist options
  • Save bjoerntx/6e73a1525734fc519a17c355b4315833 to your computer and use it in GitHub Desktop.
Save bjoerntx/6e73a1525734fc519a17c355b4315833 to your computer and use it in GitHub Desktop.
public class VersionedDocument {
// member fields
private TextControl _textControl;
private string _filename;
// properties
public List<EmbeddedFile> Attachments { get; set; } = new List<EmbeddedFile>();
// constructor
// attach a TextControl and set filename
public VersionedDocument(TextControl textControl, string filename) {
_textControl = textControl;
_filename = filename;
}
// saves the current version as the visible representation
// and attaches the current version to the attachments
public void SaveDocument() {
// save current document from connected TextControl
byte[] baCurrentDocument;
_textControl.Save(out baCurrentDocument, BinaryStreamType.InternalUnicodeFormat);
// create a unique filename
var uniqueFilename = Guid.NewGuid().ToString() + ".tx";
// add the latest attachment
Attachments.Add(new EmbeddedFile(uniqueFilename, baCurrentDocument, null));
// use a temporary ServerTextControl to save the document
using (ServerTextControl tx = new TXTextControl.ServerTextControl()) {
tx.Create();
tx.Load(baCurrentDocument, BinaryStreamType.InternalUnicodeFormat);
// set the embedded files using the SaveSettings
SaveSettings saveSettings = new SaveSettings() {
EmbeddedFiles = Attachments.ToArray()
};
// save the file
tx.Save(_filename, StreamType.AdobePDF, saveSettings);
}
}
public void LoadDocument(string filename) {
// temporary ServerTextControl to handle attachments
using (ServerTextControl tx = new ServerTextControl()) {
tx.Create();
LoadSettings ls = new LoadSettings() {
PDFImportSettings = PDFImportSettings.LoadEmbeddedFiles
};
// load the PDF document
try {
tx.Load(filename, StreamType.AdobePDF, ls);
}
catch { throw; }
// store attachments
Attachments = ls.EmbeddedFiles?.ToList();
// get latest attachment
var latestAttachment = Attachments.OrderByDescending(c => c.CreationDate).First();
// load attachment into connected TextControl
try {
_textControl.Load(
(byte[])latestAttachment.Data,
BinaryStreamType.InternalUnicodeFormat);
}
catch { throw; }
// set the current filename
_filename = filename;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment