public bool Open(string filename, string password) { if (!string.IsNullOrEmpty(_fileName) && useLock && _fileName.Equals(filename)) { if (mp == null) { _pass = password; mp = new MuPDF(_fileName, _pass, !useLock); } return(mp != null); } _fileName = filename; _pass = password; if (!string.IsNullOrEmpty(_fileName)) { mp = new MuPDF(_fileName, _pass, !useLock); } bool ret = mp != null; if (!useLock && mp != null) { mp.Dispose(); mp = null; } return(ret); }
internal void Flush() { if (!useLock && mp != null) { mp.Dispose(); mp = null; } }
private void Clean() { if (mp != null) { mp.Dispose(); mp = null; } page = 0; _fileName = null; _pass = null; }
public PDF(string fileName) : base(fileName) { MuPDF pdf = null; pdf = new MuPDF(fileName, ""); pageCount = pdf.PageCount; if (pageCount < 1) { throw new Exception("Could not open PDF."); } pdf.Dispose(); }
public IActionResult Image(Guid id, int size, string extension) { const string pngContentType = "image/png"; const string svgContentType = "image/svg+xml"; var virtualFileResult = File(Url.Content("~/images/file.svg"), svgContentType); #if DNX451 if (size >= 10 * 1024 * 1024) { return(virtualFileResult); } var serverApi = HttpContext.GetServerApi(); var file = serverApi.GetFileChunk(id, 0, size); try { if (file != null) { int page = 1; int dpi = 150; RenderType RenderType = RenderType.RGB; bool rotateAuto = false; string password = ""; var fileName = $"tmp/{id}{extension}"; using (var fileStream = System.IO.File.Create(fileName)) fileStream.Write(file, 0, file.Length); byte[] thumbnailContent; using (MuPDF pdfDoc = new MuPDF(fileName, password)) { pdfDoc.Page = page; Bitmap bm = pdfDoc.GetBitmap(0, 0, dpi, dpi, 0, RenderType, rotateAuto, false, 0); HttpContext.Response.ContentType = pngContentType; using (var ms = new MemoryStream()) { bm.Save(ms, ImageFormat.Png); thumbnailContent = ms.ToArray(); } } System.IO.File.Delete(fileName); return(File(thumbnailContent, pngContentType, $"{id}.png")); } } catch (Exception ex) { _logger.LogWarning(1, "Unable to generate thumbnail for file", ex); } #endif return(virtualFileResult); }
internal List <Tiff.PageInfo> GetBitmapsCollectionFromFile(string fileName, int startPage, int endPage, int dpiX, int dpiY, bool color) { var imagesToSave = new List <Tiff.PageInfo>(); if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName)) { return(imagesToSave); } string uP = "", oP = ""; Dictionary <int, Controls.PdfViewControl.PageInfo> pInfo = Refresh(fileName, ref oP, ref uP); if (pInfo == null || pInfo.Count == 0) { return(imagesToSave); } try { using (MuPDF mp = new MuPDF(fileName, oP, true)) { if (mp == null) { return(imagesToSave); } int stP = (startPage <= 0 ? 1 : startPage), endP = (endPage <= 0 || endPage > mp.PageCount ? mp.PageCount : endPage); pInfo = pInfo.Where(x => x.Key >= stP && x.Key <= endP).ToDictionary(x => x.Key, x => x.Value); foreach (var p in pInfo) { mp.Page = p.Key; Bitmap bm = mp.GetBitmap((int)Math.Round(mp.Width / 72.0 * dpiX), (int)Math.Round(mp.Height / 72.0 * dpiY), dpiX, dpiY, 0, color ? RenderType.RGB : RenderType.Monochrome, true, false, 0); imagesToSave.Add(new Tiff.PageInfo { Image = bm }); } } } catch (Exception ex) { Data.Env.WriteToLog(ex); } return(imagesToSave); }
internal Bitmap GetBitmap(int width, int height, float dpix, float dpiy, int rotation, RenderType renderType, bool rotateLandscapePages, bool convertToLetter, int maxSize) { if (checkMP()) { Bitmap bmp = mp.GetBitmap(width, height, dpix, dpiy, rotation, renderType, rotateLandscapePages, convertToLetter, maxSize); if (!useLock) { mp.Dispose(); mp = null; } return(bmp); } return(null); }
public static List <Tiff.PageInfo> GetPDFImages(string fileName, int from, int to) { var imagesToSave = new List <Tiff.PageInfo>(); try { if (!File.Exists(fileName)) { return(imagesToSave); } using (var mp = new MuPDF(fileName, "", true)) { int start = (@from > 0) ? @from : 1; int finish = (to > 0 && to <= mp.PageCount) ? to : mp.PageCount; if (start > finish) { finish = start - finish; start -= finish; finish += start; } if (finish > mp.PageCount) { finish = mp.PageCount; } int i = start; var pages = new int[finish - start + 1]; pages = pages.Select(x => i++).ToArray(); foreach (var p in pages) { mp.Page = p; Bitmap bm = mp.GetBitmap((int)Math.Round(mp.Width / 72.0 * 96.0), (int)Math.Round(mp.Height / 72.0 * 96.0), 96f, 96f, 0, RenderType.RGB, true, false, 0); imagesToSave.Add(new Tiff.PageInfo { Image = bm, Compression = new CompressionInfo() }); } } } catch (Exception ex) { Data.Env.WriteToLog(ex); } return(imagesToSave); }
/// <summary> /// Ctor. /// </summary> /// <param name="path">The path to the document.</param> /// <param name="renderWidth">The width of the rendered pages. Must be > 0.</param> /// <param name="renderDPI">The dpi to use when rendering the pages. Must be > 0.</param> /// <param name="password">The password (null if none).</param> /// <exception cref="Pdf2KTException">If the document cannot be opened.</exception> public PDFDocument(string path, int renderWidth = 800, int renderDPI = 96, string password = null) { RenderWidth = renderWidth; RenderDPI = renderDPI; _path = path; try { _mupdf = new MuPDF(path, password); _mupdf.AntiAlias = true; } catch (Exception e) { throw new Pdf2KTException("Error while opening PDF document.", e); } }
private void loadPdf(string pdfFilename) { MuPDF muPdf = new MuPDF(pdfFilename, ""); pageCount = muPdf.PageCount; Array.Resize(ref bitmaps, pageCount); MuPDF pdfPage; for (int page = 1; page <= pageCount; page++) { pdfPage = new MuPDF(pdfFilename, ""); pdfPage.Page = page; bitmaps[page - 1] = pdfPage.GetBitmap(450, 0, 300, 300, 0, RenderType.RGB, false, false, 10000000); } numericUpDownPageSelector.Value = 1; pictureBox1.Image = bitmaps[0]; }
private bool checkMP() { if (useLock) { return(mp != null); } if (mp == null) { mp = new MuPDF(_fileName, _pass, !useLock); if (page > 0 && page <= mp.PageCount) { mp.Page = page; } } return(mp != null); }
public override Bitmap LoadPage(int pageNumber) { if (!File.Exists(fileName)) { throw new Exception("File does not exist."); } if (bmp != null) { bmp.Dispose(); } var pdf = new MuPDF(fileName, ""); pdf.Page = pageNumber; pdf.AntiAlias = true; int width = (int)(pdf.Width * resolution / 72.0F); int height = (int)(pdf.Height * resolution / 72.0F); int estMemUsageMB = (int)Math.Ceiling(width * height * 3.0 / 1024 / 1024); Debug.WriteLine("Estimated memory {0} MB", estMemUsageMB); System.Runtime.MemoryFailPoint mfp = null; try { mfp = new System.Runtime.MemoryFailPoint(estMemUsageMB); bmp = pdf.GetBitmap(width, height, 72, 72, 0, RenderType.RGB, false, false, 0); } catch (InsufficientMemoryException) { throw new Exception("Not enough memory."); } finally { mfp.Dispose(); pdf.Dispose(); } return(bmp); }
List<BoundingBoxPair> readPDFBox(string inputPDFFileName, List<int> pages, string boxname) { try { using (var mupdf = new MuPDF(Path.Combine(GetToolsPath(), "mudraw.exe"))) { if (controller_ != null) controller_.appendOutput("Getting the size of PDFBox...\n"); var rv = new List<BoundingBoxPair>(); var doc = mupdf.Execute<int>("open_document", Path.Combine(workingDir, inputPDFFileName)); if (doc == 0) return null; foreach (var p in pages) { if (abort) { if (controller_ != null) controller_.appendOutput(Properties.Resources.STOPCONVERTMSG + "\n"); return null; } int rotate = 0; BoundingBox box = new BoundingBox(), media = new BoundingBox(); const int repeatTimes = 10; for (int i = 1; i <= repeatTimes; ++i) { try { var page = mupdf.Execute<int>("load_page", doc, p - 1); media = mupdf.Execute< BoundingBox>("pdfbox_page", page, "media"); box = mupdf.Execute<BoundingBox>("pdfbox_page", page, boxname); rotate = mupdf.Execute<int>("rotate_page", page); break; } catch (Exception) { mupdf.ClearError(); if (i == repeatTimes) throw; } } BoundingBox bb; switch (rotate) { default: case 0: bb = new BoundingBox(box.Left - media.Left, box.Bottom - media.Bottom, box.Right - media.Left, box.Top - media.Bottom); break; case 90: bb = new BoundingBox(box.Bottom - media.Bottom, media.Right - box.Right, box.Top - media.Bottom, media.Right - box.Left); break; case 180: bb = new BoundingBox(media.Right - box.Right, media.Top - box.Top, media.Right - box.Left, media.Top - box.Bottom); break; case 270: bb = new BoundingBox(media.Top - box.Top, box.Left - media.Left, media.Top - box.Bottom, box.Right - media.Left); break; } if (controller_ != null) controller_.appendOutput(bb.ToString() + " (Page " + p + ")\n"); rv.Add(new BoundingBoxPair(bb.HiresBBToBB(), bb)); } if (controller_ != null) controller_.appendOutput("\n"); return rv; } } catch (Exception e) { if (controller_ != null) controller_.appendOutput(e.Message + "\n"); #if DEBUG System.Diagnostics.Debug.WriteLine(e.StackTrace); #endif return null; } }
bool pdfinfo(string file, out int page, out int version) { page = -1;version = -1; using (var mupdf = new MuPDF(Path.Combine(GetToolsPath(), "mudraw.exe"))) { try { int doc = mupdf.Execute<int>("open_document", Path.Combine(workingDir, file)); const int repeatTimes = 10; for (int i = 1; i <= repeatTimes; ++i) { try { if (page == -1) page = mupdf.Execute<int>("count_pages", doc); if (version == -1) version = mupdf.Execute<int>("version_document", doc); return true; } catch (Exception) { mupdf.ClearError(); if (i == repeatTimes) throw; } } } catch (Exception e) { if (controller_ != null) controller_.appendOutput(Properties.Resources.FAIL_PDFPAGES + "\n" + e.Message); return false; } } return false; }
public static byte[] ConvertPdfToTiff(byte[] image, float dpi, RenderType type, bool rotateLandscapePages, bool shrinkToLetter, int maxSizeInPdfPixels, string pdfPassword) { byte[] output = null; if (image == null) { throw new ArgumentNullException("image"); } using (MuPDF pdfDoc = new MuPDF(image, pdfPassword)) { using (MemoryStream outputStream = new MemoryStream()) { ImageCodecInfo info = null; foreach (ImageCodecInfo ice in ImageCodecInfo.GetImageEncoders()) { if (ice.MimeType == "image/tiff") { info = ice; } } Bitmap saveTif = null; pdfDoc.AntiAlias = false; for (int i = 1; i <= pdfDoc.PageCount; i++) { int Width = 0; //Zero for no resize. int Height = 0; //Zero for autofit height to width. pdfDoc.Page = i; Bitmap FirstImage = pdfDoc.GetBitmap(Width, Height, dpi, dpi, 0, type, rotateLandscapePages, shrinkToLetter, maxSizeInPdfPixels); if (FirstImage == null) { throw new Exception("Unable to convert pdf to tiff!"); } using (EncoderParameters ep = new EncoderParameters(2)) { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame); ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW); if (type == RenderType.Monochrome) { ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4); } if (i == 1) { saveTif = FirstImage; saveTif.Save(outputStream, info, ep); } else { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); saveTif.SaveAdd(FirstImage, ep); FirstImage.Dispose(); } if (i == pdfDoc.PageCount) { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush); saveTif.SaveAdd(ep); saveTif.Dispose(); } } } output = outputStream.ToArray(); } } return(output); }
public static bool ConvertPdfToTiff(string sourceFile, string outputFile, float dpi, RenderType type, bool rotateLandscapePages, bool shrinkToLetter, int maxSizeInPdfPixels, string pdfPassword) { bool output = false; if (string.IsNullOrEmpty(sourceFile) || string.IsNullOrEmpty(outputFile)) { throw new ArgumentNullException(); } using (MuPDF pdfDoc = new MuPDF(sourceFile, pdfPassword, true)) { using (FileStream outputStream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { ImageCodecInfo info = null; foreach (ImageCodecInfo ice in ImageCodecInfo.GetImageEncoders()) { if (ice.MimeType == "image/tiff") { info = ice; } } Bitmap saveTif = null; pdfDoc.AntiAlias = false; for (int i = 1; i <= pdfDoc.PageCount; i++) { pdfDoc.Page = i; Bitmap FirstImage = pdfDoc.GetBitmap(0, 0, dpi, dpi, 0, type, rotateLandscapePages, shrinkToLetter, maxSizeInPdfPixels); if (FirstImage == null) { throw new Exception("Unable to convert pdf to tiff!"); } using (EncoderParameters ep = new EncoderParameters(2)) { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame); ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW); if (type == RenderType.Monochrome) { ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4); } if (i == 1) { saveTif = FirstImage; saveTif.Save(outputStream, info, ep); } else { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); saveTif.SaveAdd(FirstImage, ep); FirstImage.Dispose(); } if (i == pdfDoc.PageCount) { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush); saveTif.SaveAdd(ep); saveTif.Dispose(); } } } } if (File.Exists(outputFile)) { output = true; } } return(output); }
public static bool ConvertPdfToFaxTiff(string sourceFile, string outputFile, float dpi, bool shrinkToLetter, string pdfPassword) { bool output = false; const long Compression = (long)EncoderValue.CompressionCCITT4; using (MuPDF pdfDoc = new MuPDF(sourceFile, pdfPassword, true)) { using (FileStream outputStream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { ImageCodecInfo info = null; foreach (ImageCodecInfo ice in ImageCodecInfo.GetImageEncoders()) { if (ice.MimeType == "image/tiff") { info = ice; } } Bitmap saveTif = null; pdfDoc.AntiAlias = false; for (int i = 1; i <= pdfDoc.PageCount; i++) { int Width = 0;//Zero for no resize. //int Height = 0;//Zero for autofit height to width. float DpiX = dpi; float DpiY = dpi; pdfDoc.Page = i; if (dpi == 200) { Width = 1728; DpiX = 204; DpiY = 196; } else if (dpi == 300) { Width = 2592; } else if (dpi == 400) { Width = 3456; } Bitmap FirstImage = pdfDoc.GetBitmap(Width, 0, DpiX, DpiY, 0, RenderType.Monochrome, true, shrinkToLetter, 0); if (FirstImage == null) { throw new Exception("Unable to convert pdf to tiff!"); } using (EncoderParameters ep = new EncoderParameters(2)) { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame); ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, Compression); if (i == 1) { saveTif = FirstImage; saveTif.Save(outputStream, info, ep); } else { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); saveTif.SaveAdd(FirstImage, ep); FirstImage.Dispose(); } if (i == pdfDoc.PageCount) { ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush); saveTif.SaveAdd(ep); saveTif.Dispose(); } } } } if (File.Exists(outputFile)) { output = true; } } return(output); }
static void PDFEmbed(string file, string text) { var tmpdir = Path.GetTempPath(); var tmp = TempFilesDeleter.GetTempFileName(".pdf", tmpdir); tmp = Path.Combine(tmpdir, tmp); using (var tmp_deleter = new TempFilesDeleter(tmpdir)) { tmp_deleter.AddFile(tmp); using (var mupdf = new MuPDF(mudraw)) { var doc = mupdf.Execute<int>("open_document", file); if (doc == 0) return; var page = mupdf.Execute<int>("load_page", doc, 0); if (page == 0) return; var annot = mupdf.Execute<int>("create_annot", page, "Text"); if (annot == 0) return; mupdf.Execute("set_annot_contents", annot, ChangeReturnCode(PDFsrcHead + System.Environment.NewLine + text, "\n")); mupdf.Execute("set_annot_flag", annot, 35); mupdf.Execute("write_document", doc, tmp); } if (File.Exists(tmp)) { File.Delete(file); File.Move(tmp, file); } } }
static string PDFRead(string file) { var srcHead = PDFsrcHead + System.Environment.NewLine; using (var mupdf = new MuPDF(mudraw)) { var doc = mupdf.Execute<int>("open_document", file); if (doc == 0) return null; var page = mupdf.Execute<int>("load_page", doc, 0); if (page == 0) return null; var annot = mupdf.Execute<int>("first_annot", page); while (annot != 0) { var rect = mupdf.Execute<BoundingBox>("bound_annot", annot); if(rect.Width == 0 && rect.Height == 0) { if (mupdf.Execute<string>("annot_type", annot) == "Text") { var text = mupdf.Execute<string>("annot_contents", annot); text = ChangeReturnCode(text); if (text.StartsWith(srcHead)) { return text.Substring(srcHead.Length); } } } annot = mupdf.Execute<int>("next_annot", annot); } } return null; }