PDFDocument.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. using Paroxe.PdfRenderer.WebGL;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Runtime.InteropServices;
  6. using UnityEngine;
  7. using Paroxe.PdfRenderer.Internal;
  8. using System.IO;
  9. namespace Paroxe.PdfRenderer
  10. {
  11. /// <summary>
  12. /// Represents a PDF document. This class is the entry point of all functionalities.
  13. /// </summary>
  14. public class PDFDocument : IPDFDocumentInternal, IDisposable
  15. {
  16. private bool m_Disposed;
  17. private bool m_Disposing;
  18. private IntPtr m_NativePointer;
  19. private GCHandle m_BufferHandle;
  20. private byte[] m_DocumentBuffer;
  21. private bool m_ValidDocument;
  22. private PDFRenderer m_Renderer;
  23. private HashSet<PDFPage> m_LoadedPages;
  24. public static PDFJS_Promise<PDFDocument> LoadDocumentFromUrlAsync(string url)
  25. {
  26. PDFJS_Promise<PDFDocument> documentPromise = new PDFJS_Promise<PDFDocument>();
  27. #if !UNITY_WEBGL || UNITY_EDITOR
  28. PDFJS_Library.Instance.PreparePromiseCoroutine(LoadDocumentFromWWWCoroutine, documentPromise, url).Start();
  29. #else
  30. LoadDocumentParameters parameters = new LoadDocumentParameters();
  31. parameters.url = url;
  32. PDFJS_Library.Instance.PreparePromiseCoroutine(LoadDocumentCoroutine, documentPromise, parameters).Start();
  33. #endif
  34. return documentPromise;
  35. }
  36. #if !UNITY_WEBGL || UNITY_EDITOR
  37. private static IEnumerator LoadDocumentFromWWWCoroutine(PDFJS_PromiseCoroutine promiseCoroutine, IPDFJS_Promise promise, object urlString)
  38. {
  39. PDFJS_Promise<PDFDocument> documentPromise = promise as PDFJS_Promise<PDFDocument>;
  40. PDFLibrary.Instance.EnsureInitialized();
  41. while (!PDFLibrary.Instance.IsInitialized)
  42. yield return null;
  43. string url = urlString as string;
  44. PDFWebRequest www = new PDFWebRequest(url);
  45. www.SendWebRequest();
  46. yield return www;
  47. if (string.IsNullOrEmpty(www.error))
  48. {
  49. documentPromise.HasFinished = true;
  50. documentPromise.HasSucceeded = true;
  51. documentPromise.HasReceivedJSResponse = true;
  52. documentPromise.Result = new PDFDocument(www.bytes);
  53. promiseCoroutine.ExecuteThenAction(true, documentPromise.Result);
  54. }
  55. else
  56. {
  57. documentPromise.HasFinished = true;
  58. documentPromise.HasSucceeded = false;
  59. promiseCoroutine.ExecuteThenAction(false, null);
  60. }
  61. www.Dispose();
  62. www = null;
  63. }
  64. #endif
  65. public static PDFJS_Promise<PDFDocument> LoadDocumentFromBytesAsync(byte[] bytes)
  66. {
  67. PDFJS_Promise<PDFDocument> documentPromise = new PDFJS_Promise<PDFDocument>();
  68. #if !UNITY_WEBGL || UNITY_EDITOR
  69. documentPromise.HasFinished = true;
  70. documentPromise.HasSucceeded = true;
  71. documentPromise.HasReceivedJSResponse = true;
  72. documentPromise.Result = new PDFDocument(bytes);
  73. #else
  74. LoadDocumentParameters parameters = new LoadDocumentParameters();
  75. parameters.bytes = bytes;
  76. PDFJS_Library.Instance.PreparePromiseCoroutine(LoadDocumentCoroutine, documentPromise, parameters).Start();
  77. #endif
  78. return documentPromise;
  79. }
  80. public PDFDocument(IntPtr nativePointer)
  81. {
  82. PDFLibrary.AddRef("PDFDocument");
  83. m_NativePointer = nativePointer;
  84. m_ValidDocument = true;
  85. }
  86. #if !UNITY_WEBGL || UNITY_EDITOR
  87. /// <summary>
  88. /// Open PDF Document with the specified byte array.
  89. /// </summary>
  90. /// <param name="buffer"></param>
  91. public PDFDocument(byte[] buffer)
  92. : this(buffer, "")
  93. { }
  94. /// <summary>
  95. /// Open PDF Document with the specified byte array.
  96. /// </summary>
  97. /// <param name="buffer"></param>
  98. /// <param name="password">Can be null or empty</param>
  99. public PDFDocument(byte[] buffer, string password)
  100. {
  101. PDFLibrary.AddRef("PDFDocument");
  102. CommonInit(buffer, password);
  103. }
  104. /// <summary>
  105. /// Open PDF Document located at the specified path
  106. /// </summary>
  107. /// <param name="filePath"></param>
  108. public PDFDocument(string filePath)
  109. : this(filePath, "")
  110. { }
  111. /// <summary>
  112. ///
  113. /// </summary>
  114. /// <param name="filePath"></param>
  115. /// <param name="password">Can be null or empty</param>
  116. public PDFDocument(string filePath, string password)
  117. {
  118. PDFLibrary.AddRef("PDFDocument");
  119. CommonInit(File.ReadAllBytes(filePath), password);
  120. }
  121. #endif
  122. ~PDFDocument()
  123. {
  124. Dispose(false);
  125. }
  126. protected virtual void Dispose(bool _)
  127. {
  128. if (!m_Disposed)
  129. {
  130. m_Disposing = true;
  131. lock (PDFLibrary.nativeLock)
  132. {
  133. if (m_NativePointer != IntPtr.Zero)
  134. {
  135. if (m_LoadedPages != null)
  136. {
  137. foreach (PDFPage page in m_LoadedPages)
  138. page.Dispose();
  139. m_LoadedPages = null;
  140. }
  141. #if UNITY_WEBGL && !UNITY_EDITOR
  142. NativeMethods.PDFJS_CloseDocument(m_NativePointer.ToInt32());
  143. #else
  144. NativeMethods.FPDF_CloseDocument(m_NativePointer);
  145. #endif
  146. if (m_DocumentBuffer != null)
  147. m_BufferHandle.Free();
  148. m_NativePointer = IntPtr.Zero;
  149. }
  150. }
  151. PDFLibrary.RemoveRef("PDFDocument");
  152. m_Disposing = false;
  153. m_Disposed = true;
  154. }
  155. }
  156. void IPDFDocumentInternal.OnPageClose(PDFPage page)
  157. {
  158. if (m_LoadedPages != null && !m_Disposing)
  159. m_LoadedPages.Remove(page);
  160. }
  161. public void Dispose()
  162. {
  163. Dispose(true);
  164. GC.SuppressFinalize(this);
  165. }
  166. /// <summary>
  167. /// Return a convenience PDFRenderer instance.
  168. /// </summary>
  169. public PDFRenderer Renderer
  170. {
  171. get
  172. {
  173. if (m_Renderer == null)
  174. m_Renderer = new PDFRenderer();
  175. return m_Renderer;
  176. }
  177. }
  178. /// <summary>
  179. /// The byte array of the document.
  180. /// </summary>
  181. public byte[] DocumentBuffer
  182. {
  183. get { return m_DocumentBuffer; }
  184. }
  185. /// <summary>
  186. /// Return if the document is valid. The document can be invalid if the password is invalid or if the
  187. /// document itseft is corrupted. See PDFLibrary.GetLastError.
  188. /// </summary>
  189. public bool IsValid
  190. {
  191. get { return m_ValidDocument; }
  192. }
  193. public IntPtr NativePointer
  194. {
  195. get { return m_NativePointer; }
  196. }
  197. public int GetPageCount()
  198. {
  199. #if UNITY_WEBGL && !UNITY_EDITOR
  200. return NativeMethods.PDFJS_GetPageCount(m_NativePointer.ToInt32());
  201. #else
  202. return NativeMethods.FPDF_GetPageCount(m_NativePointer);
  203. #endif
  204. }
  205. #if !UNITY_WEBGL || UNITY_EDITOR
  206. public Vector2 GetPageSize(int pageIndex)
  207. {
  208. double width;
  209. double height;
  210. NativeMethods.FPDF_GetPageSizeByIndex(m_NativePointer, pageIndex, out width, out height);
  211. return new Vector2((float)width, (float)height);
  212. }
  213. #endif
  214. #if !UNITY_WEBGL || UNITY_EDITOR
  215. public int GetPageWidth(int pageIndex)
  216. {
  217. double width;
  218. double height;
  219. NativeMethods.FPDF_GetPageSizeByIndex(m_NativePointer, pageIndex, out width, out height);
  220. return (int)width;
  221. }
  222. #endif
  223. #if !UNITY_WEBGL || UNITY_EDITOR
  224. public int GetPageHeight(int pageIndex)
  225. {
  226. double width;
  227. double height;
  228. NativeMethods.FPDF_GetPageSizeByIndex(m_NativePointer, pageIndex, out width, out height);
  229. return (int)height;
  230. }
  231. #endif
  232. #if !UNITY_WEBGL
  233. /// <summary>
  234. /// Return the root bookmark of the document.
  235. /// </summary>
  236. /// <returns></returns>
  237. public PDFBookmark GetRootBookmark()
  238. {
  239. return GetRootBookmark(null);
  240. }
  241. #endif
  242. #if !UNITY_WEBGL
  243. /// <summary>
  244. /// Return the root bookmark of the document.
  245. /// </summary>
  246. /// <param name="device">Pass the device that will receive bookmarks action</param>
  247. /// <returns></returns>
  248. public PDFBookmark GetRootBookmark(IPDFDevice device)
  249. {
  250. return new PDFBookmark(this, null, IntPtr.Zero, device);
  251. }
  252. #endif
  253. #if !UNITY_WEBGL || UNITY_EDITOR
  254. public PDFPage GetPage(int index)
  255. {
  256. PDFPage page = new PDFPage(this, index);
  257. if (m_LoadedPages == null)
  258. m_LoadedPages = new HashSet<PDFPage>();
  259. m_LoadedPages.Add(page);
  260. return page;
  261. }
  262. #endif
  263. public PDFJS_Promise<PDFPage> GetPageAsync(int index)
  264. {
  265. return PDFPage.LoadPageAsync(this, index);
  266. }
  267. private void CommonInit(byte[] buffer, string password)
  268. {
  269. m_DocumentBuffer = buffer;
  270. if (m_DocumentBuffer != null)
  271. {
  272. #if !UNITY_WEBGL || UNITY_EDITOR
  273. m_BufferHandle = GCHandle.Alloc(m_DocumentBuffer, GCHandleType.Pinned);
  274. m_NativePointer = NativeMethods.FPDF_LoadMemDocument(m_BufferHandle.AddrOfPinnedObject(), m_DocumentBuffer.Length, password);
  275. #endif
  276. m_ValidDocument = (m_NativePointer != IntPtr.Zero);
  277. }
  278. else
  279. {
  280. m_ValidDocument = false;
  281. }
  282. }
  283. #if UNITY_WEBGL && !UNITY_EDITOR
  284. class LoadDocumentParameters
  285. {
  286. public string url;
  287. public byte[] bytes;
  288. }
  289. private static IEnumerator LoadDocumentCoroutine(PDFJS_PromiseCoroutine promiseCoroutine, IPDFJS_Promise promise, object pars)
  290. {
  291. PDFJS_Promise<PDFDocument> documentPromise = promise as PDFJS_Promise<PDFDocument>;
  292. PDFLibrary.Instance.EnsureInitialized();
  293. while (!PDFLibrary.Instance.IsInitialized)
  294. yield return null;
  295. LoadDocumentParameters parameters = pars as LoadDocumentParameters;
  296. if (!string.IsNullOrEmpty(parameters.url))
  297. NativeMethods.PDFJS_LoadDocumentFromURL(promise.PromiseHandle, parameters.url);
  298. else
  299. NativeMethods.PDFJS_LoadDocumentFromBytes(promise.PromiseHandle, Convert.ToBase64String(parameters.bytes));
  300. while (!promiseCoroutine.Promise.HasReceivedJSResponse)
  301. yield return null;
  302. if (documentPromise.HasSucceeded)
  303. {
  304. int documentHandle = int.Parse(promiseCoroutine.Promise.JSObjectHandle);
  305. PDFDocument document = new PDFDocument(new IntPtr(documentHandle));
  306. documentPromise.Result = document;
  307. documentPromise.HasFinished = true;
  308. promiseCoroutine.ExecuteThenAction(true, documentHandle);
  309. }
  310. else
  311. {
  312. documentPromise.Result = null;
  313. documentPromise.HasFinished = true;
  314. promiseCoroutine.ExecuteThenAction(false, null);
  315. }
  316. }
  317. #endif
  318. }
  319. public interface IPDFDocumentInternal
  320. {
  321. void OnPageClose(PDFPage page);
  322. }
  323. }