Anonymous Anonymous - 1 month ago
266 0

No description

C#

MobilePDFAnnotationMergeService.cs

public class MobilePDFAnnotationMergeService : IPDFAnnotationMergeService
	{
		public bool Merge(string oldFile, string newFile)
		{
			bool hasAnnotations = false;

			if (File.Exists(oldFile))
			{
				using (var oldStream = File.Open(oldFile, FileMode.Open))
				{
					oldStream.Position = 0;

					using (var oldDoc = new PDFDoc(oldStream))
					{
						oldDoc.Lock();

						hasAnnotations = DisplayUtils.HasAnnotations(oldDoc);

						if (hasAnnotations)
						{
							// Load the old annotations
							using (var oldAnnotations = oldDoc.FDFExtract(PDFDoc.ExtractFlag.e_annots_only))
							{
								// Merge the old annotations into the new document
								using (var newStream = File.Open(newFile, FileMode.Open))
								{
									newStream.Position = 0;

									using (var newDoc = new PDFDoc(newStream))
									{
										newDoc.Lock();

										newDoc.FDFMerge(oldAnnotations);

										newDoc.Save(newFile,
													pdftron.SDF.SDFDoc.SaveOptions.e_linearized);

										newDoc.Unlock();

										newDoc.Close();
									}

									newStream.Close();
								}

								oldAnnotations.Close();
							}
						}
						else
						{
							using (var newStream = File.Open(newFile, FileMode.Open))
							{
								newStream.Position = 0;

								using (var newDoc = new PDFDoc(newStream))
								{
									newDoc.Lock();
									hasAnnotations = DisplayUtils.HasAnnotations(newDoc);
									newDoc.Unlock();
									newDoc.Close();
								}

								newStream.Close();
							}
						}

						oldDoc.Unlock();
						oldDoc.Close();
					}

					oldStream.Close();
				}

				File.Delete(oldFile);
			}
			else
			{
				using (var newStream = File.Open(newFile, FileMode.Open))
				{
					newStream.Position = 0;

					using (var newDoc = new PDFDoc(newStream))
					{
						newDoc.Lock();
						hasAnnotations = DisplayUtils.HasAnnotations(newDoc);
						newDoc.Unlock();
						newDoc.Close();
					}

					newStream.Close();
				}
			}

			File.Move(newFile, oldFile);

			return hasAnnotations;
		}
	}