private void RemoveFile(PDFFile file) { Files.Remove(file); RaisePropertyChanged(() => this.Files); RemovePDFFileCommand.RaiseCanExecuteChanged(); MergeFilesCommand.RaiseCanExecuteChanged(); }
private int printShow(string url) { int isOK = 0; PDFFile file = PDFFile.Open(url); PrinterSettings settings = new PrinterSettings(); System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument(); settings.PrinterName = "\\\\192.168.2.93\\Brother DCP-7030 Printer"; settings.PrintToFile = false; //设置纸张大小(可以不设置,取默认设置)3.90 in, 8.65 in //PaperSize ps = new PaperSize("test", 4, 9); //ps.RawKind = 9; //如果是自定义纸张,就要大于118,(A4值为9,详细纸张类型与值的对照请看http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx) O2S.Components.PDFRender4NET.Printing.PDFPrintSettings pdfPrintSettings = new O2S.Components.PDFRender4NET.Printing.PDFPrintSettings(settings); //pdfPrintSettings.PaperSize = ps; pdfPrintSettings.PageScaling = O2S.Components.PDFRender4NET.Printing.PageScaling.FitToPrinterMarginsProportional; pdfPrintSettings.PrinterSettings.Copies = 1; try { file.Print(pdfPrintSettings); isOK = 1; } catch (Exception) { isOK = -1; throw; } finally { file.Dispose(); } return(isOK); }
public static void Main(string[] args) { // Extract the page content from the source file. FileStream stream = File.OpenRead("input.pdf"); PDFFile source = new PDFFile(stream); PDFPageContent pageContent = source.ExtractPageContent(0); stream.Close(); PDFFixedDocument document = new PDFFixedDocument(); document.OptionalContentProperties = new PDFOptionalContentProperties(); PDFPage page = document.Pages.Add(); // Create an optional content group (layer) for the extracted page content. PDFOptionalContentGroup ocg = new PDFOptionalContentGroup(); ocg.Name = "Embedded page"; ocg.VisibilityState = PDFOptionalContentGroupVisibilityState.AlwaysVisible; ocg.PrintState = PDFOptionalContentGroupPrintState.NeverPrint; // Draw the extracted page content in the layer page.Canvas.BeginOptionalContentGroup(ocg); page.Canvas.DrawFormXObject(pageContent, 0, 0, page.Width, page.Height); page.Canvas.EndOptionalContentGroup(); // Build the display tree for the optional content PDFOptionalContentDisplayTreeNode ocgNode = new PDFOptionalContentDisplayTreeNode(ocg); document.OptionalContentProperties.DisplayTree.Nodes.Add(ocgNode); using (FileStream output = File.Create("EmbedPageAsLayer.pdf")) { document.Save(output); } }
public async Task MonitorPageUpdateLateRenderRequest() { // In this test we make sure not to access the # of pages. var f = new dummyFile(); var data = await TestUtils.GetFileAsBytes("test.pdf"); f.GetStream = () => { return(Observable.Return(new StreamReader(new MemoryStream(data)))); }; var dc = new dummyCache(); var vm = new FileDownloadController(f, dc); var pf = new PDFFile(vm); // Setup the look before we setup the render. var pupdatetmp = pf.GetPageStreamAndCacheInfo(5).Timeout(TimeSpan.FromSeconds(5)).FirstAsync(); vm.DownloadOrUpdate.Execute(null); var pupdate = await pupdatetmp; // Make sure what came back looks ok! Assert.IsNotNull(pupdate); var page = await pupdate.Item2.FirstAsync(); Assert.AreEqual(5, (int)page.Index); }
public async Task DownloadFileFromCacheNotThereYet() { var f = new dummyFile(); f.GetStream = () => { throw new InvalidOperationException(); }; // Install original data in cache var dc = new dummyCache(); var data = await TestUtils.GetFileAsBytes("test.pdf"); await f.SaveFileInCache(f.DateToReturn, data, dc); // Create VM's and hook them up. var vm = new FileDownloadController(f, dc); var pf = new PDFFile(vm); var dummy1 = pf.NumberOfPages; // Start it off Debug.WriteLine("FIring the download or update"); vm.DownloadOrUpdate.Execute(null); await pf.WhenAny(x => x.NumberOfPages, x => x.Value) .Where(x => x != 0) .Timeout(TimeSpan.FromSeconds(1), Observable.Return <int>(0)) .FirstAsync(); Assert.AreEqual(10, pf.NumberOfPages); }
public void CloseFile() { //this.FileName = string.Empty; this.CurrentPage = 0; this.PageScale = 1; this.HScroll = false; this.vScrollBar1.Value = 0; this.vScrollBar1.Maximum = this.panelContent.Height; if (pdfFile != null) { pdfFile.Dispose(); pdfFile = null; } foreach (var page in this.Pages) { if (page.PageControl != null) { this.panelContent.Controls.Remove(page.PageControl); page.PageControl.Dispose(); page.Dispose(); } } this.Pages.Clear(); }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> private void ConvertPDF2ImageO2S(string pdfInputPath) { // Is NULL if (pdfInputPath == null) { m_nConvertStatus = EErrorType.PTJ_FILENAME_EMPTY; } PDFFile pdfFile = PDFFile.Open(pdfInputPath); try { m_nTotalPage = pdfFile.PageCount; PrintLog("ConvertStatus:" + (int)ConvertStatus.START + " " + 0 + " " + m_nTotalPage); // start to convert each page for (int i = 0; i < m_nTotalPage; i++) { PrintLog("ConvertStatus:" + (int)ConvertStatus.ING + " " + (i + 1).ToString() + " " + m_nTotalPage); string strJPGName = m_strOutDir + "\\" + Path.GetFileNameWithoutExtension(pdfInputPath) + "_" + m_nTotalPage + "_" + (i + 1).ToString() + ".jpg"; Bitmap pageImage = pdfFile.GetPageImage(i, 56 * (int)m_dQuality); pageImage.Save(strJPGName, ImageFormat.Jpeg); pageImage.Dispose(); } } catch (Exception ex) { PrintLog(ex.Message.ToString()); m_nConvertStatus = EErrorType.PTJ_EXCEPTION_FAILED; } finally { pdfFile.Dispose(); } }
public async Task TestFileNoAutoDownload() { // Cached file, even if no auto upload, should be checked against the internet. Settings.AutoDownloadNewMeeting = false; var df = new dummyFile("test.pdf", "test.pdf"); var data = await TestUtils.GetFileAsBytes("test.pdf"); await df.SaveFileInCache(df.DateToReturn, data, Blobs.LocalStorage); // Now, we are going to update the cache, and see if it gets re-read (which it should since we have it) df.DateToReturn = "this is the second one"; var dfctl = new FileDownloadController(df); var pdfFile = new PDFFile(dfctl); var vm = new FileSlideListViewModel(pdfFile, new TimePeriod(DateTime.Now, DateTime.Now)); var list = vm.SlideThumbnails; Assert.IsNotNull(list); Assert.AreEqual(0, list.Count); dfctl.DownloadOrUpdate.Execute(null); await TestUtils.SpinWait(() => list.Count != 0, 200); await Task.Delay(10); Assert.AreEqual(10, list.Count); Assert.AreEqual(1, df.GetStreamCalled); }
public IActionResult PDFDataUpload(PDFUploadViewModel model, int fileId, string category) { //error catcher. If the user clicked the "upload" button without selecting a file, return to them the same page, and pass the category and fileId so those don't get los if (model.PDFFiles == null) { ViewBag.fileId = fileId; ViewBag.category = category; return(View()); } //save the file the user wants to upload to the correct place on the server if (ModelState.IsValid) { string uniqueFileName = null; if (model.PDFFiles != null) { string uploadsFolder = null; //create the correct path to save the file based on which accordian box the user clicked on if (fileId == 1) { uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "pdf/Osteology Data"); } else if (fileId == 2) { uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "pdf/Field Books"); } else if (fileId == 3) { uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "pdf/Archaeological Database Articles"); } else { uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "pdf/Misc Data"); } uniqueFileName = Guid.NewGuid().ToString() + "_" + model.PDFFiles.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); model.PDFFiles.CopyTo(new FileStream(filePath, FileMode.Create)); } //create a new pdf file object. Save the path, name, and FileId PDFFile newPDFFile = new PDFFile { Path = uniqueFileName, Name = model.PDFFiles.FileName, FileId = fileId }; //add the object to the database and save it _context.PDFFiles.Add(newPDFFile); _context.SaveChanges(); //return the user to the PDF data page with the context file return(RedirectToAction("PDFData", _context.PDFFiles)); } return(View()); }
public async Task FetchSlideOnlyOnce() { // Subscribe to all the slides and get back MemoryStreams for all of them // to stress out the simultaneous reading of everything. var df = new dummyFile("test.pdf", "test.pdf"); var dfctl = new FileDownloadController(df); dfctl.DownloadOrUpdate.Execute(null); var pdfFile = new PDFFile(dfctl); var vm = new FileSlideListViewModel(pdfFile, new TimePeriod(DateTime.Now, DateTime.Now)); var list = vm.SlideThumbnails; // Listen for everything to be rendered. var allImages = list .Select(item => item.PDFPageVM.ImageStream.Where(i => i != null)) .Select(strm => strm.FirstAsync()) .Select(async stream => await stream) .ToArray(); // Fire off the rendering of everything var renderOptions = Tuple.Create(PDFPageViewModel.RenderingDimension.Horizontal, (double)150, (double)150); foreach (var item in list) { item.PDFPageVM.RenderImage.Execute(renderOptions); } // And now wait for everything. await Task.WhenAll(allImages); // Make sure we had to download the file only once. Assert.AreEqual(1, df.GetStreamCalled); }
public async Task TestFileUpdated() { // First, we need to get the file into the cache. Use the infrastructure to do that. var df = new dummyFile("test.pdf", "test.pdf"); var data = await TestUtils.GetFileAsBytes("test.pdf"); await df.SaveFileInCache(df.DateToReturn, data, Blobs.LocalStorage); // Now, we are going to update the cache, and see if it gets re-read. df.DateToReturn = "this is the second one"; var dfctl = new FileDownloadController(df); var pdfFile = new PDFFile(dfctl); var vm = new FileSlideListViewModel(pdfFile, new TimePeriod(DateTime.Now, DateTime.Now)); var list = vm.SlideThumbnails; Assert.IsNotNull(list); Assert.AreEqual(0, list.Count); dfctl.DownloadOrUpdate.Execute(null); await TestUtils.SpinWait(() => list.Count != 0, 200); await Task.Delay(10); Assert.AreEqual(10, list.Count); // 2 - when we do the update. Assert.AreEqual(1, df.GetStreamCalled); }
public static bool ToImage(string pdfInputPath, string imageOutputPath, string imageName, ImageFormat imageFormat) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); Data.pageCount = pdfFile.PageCount; int startPageNum = 1; int endPageNum = Data.pageCount; Console.WriteLine(imageOutputPath); if (!Directory.Exists(Data.sourceImageDirpath)) { Directory.CreateDirectory(Data.sourceImageDirpath); } else { Directory.Delete(Data.sourceImageDirpath, true); Directory.CreateDirectory(Data.sourceImageDirpath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { startPageNum = endPageNum; endPageNum = startPageNum; } Data.OriginalImages = new List <Bitmap>(); // start to convert each page for (int i = startPageNum; i <= endPageNum; i++) { float pageWidth = (float)(pdfFile.GetPageSize(i - 1).Width / 72); //float pageHeight = (float)(pdfFile.GetPageSize(i - 1).Height / 72); float resolution = Data.panelWidth / pageWidth; //Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); Bitmap pageImage = pdfFile.GetPageImage(i - 1, resolution); //if (!Directory.Exists(imageOutputPath)) // Directory.CreateDirectory(imageOutputPath + "\\images"); pageImage.Save(imageOutputPath + "\\" + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); string imgPath = imageOutputPath + "\\" + imageName + i.ToString() + "." + imageFormat.ToString(); Data.OriginalImages.Add(new Bitmap(GetCopyImage(imgPath))); //File.Delete(imgPath); //Console.WriteLine($"page {i} converted, width:{Data.OriginalImages[i - 1].Width} height:{Data.OriginalImages[i - 1].Height}"); } pdfFile.Dispose(); //Data.OriginalImages.Clear(); //File.Delete(imageOutputPath + "\\" + imageName + "1." + imageFormat.ToString()); return(true); }
public async Task LoadVMButNoImageLoad() { // WHen this VM isn't attached to a actual View, we should not // trigger any loading or similar. All should remain very quiet. // (e.g. lazy loading). // Get the infrastructure setup var f = new dummyFile(); var data = await TestUtils.GetFileAsBytes("test.pdf"); int timesLoaded = 0; f.GetStream = () => { timesLoaded++; return(Observable.Return(new StreamReader(new MemoryStream(data)))); }; var dc = new dummyCache(); var vm = new FileDownloadController(f, dc); vm.DownloadOrUpdate.Execute(null); var pf = new PDFFile(vm); // Now, build the VM var pdfVM = new PDFPageViewModel(pf.GetPageStreamAndCacheInfo(1), dc); await TestUtils.SpinWait(() => timesLoaded != 0, 1000); Assert.AreEqual(1, timesLoaded); Assert.AreEqual(0, dc.NumberTimesGetCalled); }
public async Task SizePerpareCausesErrorsIfCalledEarly() { // Get the size stuff ready, and then call it to make sure // there are no issues with doing the size calculation. // Get the infrastructure setup var f = new dummyFile(); var data = await TestUtils.GetFileAsBytes("test.pdf"); f.GetStream = () => { return(Observable.Return(new StreamReader(new MemoryStream(data)))); }; var dc = new dummyCache(); var vm = new FileDownloadController(f, dc); var pf = new PDFFile(vm); vm.DownloadOrUpdate.Execute(null); // Now, build the VM var pdfVM = new PDFPageViewModel(pf.GetPageStreamAndCacheInfo(1), dc); // Next, fire off the size thing. var r = pdfVM.CalcRenderingSize(IWalker.ViewModels.PDFPageViewModel.RenderingDimension.Horizontal, (double)100, (double)100); Assert.IsNull(r); }
/// <summary> /// Checks to see if a file has a user password. /// </summary> /// <param name="fileName">File to check</param> /// <returns>true if the PDF file is encrypted; otherwise, it is false</returns> public static bool IsEncrypted(string fileName) { var fileType = PDFFile.GetPDFFileType(fileName, true); switch (fileType) { case PDFFileType.Unknown: case PDFFileType.EncapsulatedPostscript: case PDFFileType.Postscript: Console.WriteLine("Not a valid PDF file"); return(false); case PDFFileType.PDF17: case PDFFileType.PDF16: case PDFFileType.PDF15: case PDFFileType.PDF14: case PDFFileType.PDF13: case PDFFileType.PDF12: case PDFFileType.PDF11: case PDFFileType.PDF10: return(PDFFile.IsEncrypted(fileName)); default: throw new ArgumentOutOfRangeException(); } }
public DocumentPropertiesDialog(PDFDocument document, PDFFile file) { InitializeComponent(); _document = document; _file = file; }
public PDFTraceLogLayoutDocument(Document doc, IPDFLayoutEngine engine, PDFFile originalfile) : base(doc, engine) { this._originalFile = originalfile; if (null != this._originalFile) { PDFFileIndirectObject catRef = originalfile.DocumentCatalogRef; if (null == catRef) { throw new NullReferenceException("Document catalog could not be found in the original source document"); } this._existCatalog = originalfile.DocumentCatalog; this._existPageTree = originalfile.PageTree; if (null != this._existPageTree) { this._existPageRefs = this.GetAllPages(this._existPageTree, originalfile); } else { this._existPageRefs = new PDFObjectRef[] { } }; } }
private static string[] ExtractFiles(string sourceOddFileName, string sourceEvenFileName) { var oddFile = new PDFFile(sourceOddFileName); var oddPageCount = oddFile.GetPageCount(); var evenFile = new PDFFile(sourceEvenFileName); var evenPageCount = evenFile.GetPageCount(); var filenames = new string[oddPageCount + evenPageCount]; // Extract each page to an individual PDF file for (var i = 1; i <= oddPageCount; i++) { var pageNum = (i * 2) - 1; filenames[pageNum - 1] = $"temp-page-{pageNum}.pdf"; oddFile.ExtractPages(i, i, filenames[pageNum - 1]); } for (var i = 1; i <= evenPageCount; i++) { var pageNum = (i * 2); filenames[pageNum - 1] = $"temp-page-{pageNum}.pdf"; evenFile.ExtractPages(i, i, filenames[pageNum - 1]); } return(filenames); }
/// <summary> /// 将PDF文档转换为图片的方法 /// </summary> /// <param name="pdfInputPath">PDF文件路径</param> /// <param name="imageOutputPath">图片输出路径</param> /// <param name="imageName">生成图片的名字</param> /// <param name="startPageNum">从PDF文档的第几页开始转换</param> /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param> /// <param name="imageFormat">设置所需图片格式</param> /// <param name="definition">设置图片的清晰度,数字越大越清晰</param> public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition) { PDFFile pdfFile = PDFFile.Open(pdfInputPath); if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); } // validate pageNum if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } // start to convert each page for (int i = startPageNum; i <= endPageNum; i++) { Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition); pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); pageImage.Dispose(); } pdfFile.Dispose(); }
// For this sample to work, the following file // needs to exist: multicolumntextandimages.pdf. // Compile the corresponding sample to get this file public static void MultiPage() { //PDF4NET v5: PDFFile mctiFile = PDFFile.FromFile("Sample_MultiColumnTextAndImages-Secure.pdf", Encoding.ASCII.GetBytes("userpass")); FileStream stm = File.OpenRead("..\\..\\..\\..\\..\\SupportFiles\\content.pdf"); PDFFile file = new PDFFile(stm); // extract the content of first 4 pages //PDF4NET v5: PDFImportedContent[] ic = mctiFile.ExtractPagesContent("0-3"); PDFPageContent[] pc = file.ExtractPageContent(0, 3); // create the new document //PDF4NET v5: PDFDocument doc = new PDFDocument(); PDFFixedDocument doc = new PDFFixedDocument(); // add a page to it //PDF4NET v5: PDFPage page = doc.AddPage(); PDFPage page = doc.Pages.Add(); // draw the imported content (4 pages) on the new page //PDF4NET v5: page.Canvas.DrawImportedContent(ic[0], 0, 0, page.Width / 2, page.Height / 2); page.Canvas.DrawFormXObject(pc[0], 0, 0, page.Width / 2, page.Height / 2); //PDF4NET v5: page.Canvas.DrawImportedContent(ic[1], page.Width / 2, 0, page.Width / 2, page.Height / 2); page.Canvas.DrawFormXObject(pc[1], page.Width / 2, 0, page.Width / 2, page.Height / 2); //PDF4NET v5: page.Canvas.DrawImportedContent(ic[2], 0, page.Height / 2, page.Width / 2, page.Height / 2); page.Canvas.DrawFormXObject(pc[2], 0, page.Height / 2, page.Width / 2, page.Height / 2); //PDF4NET v5: page.Canvas.DrawImportedContent(ic[3], page.Width / 2, page.Height / 2, page.Width / 2, page.Height / 2); page.Canvas.DrawFormXObject(pc[3], page.Width / 2, page.Height / 2, page.Width / 2, page.Height / 2); // save the mixed document doc.Save("Sample_Imposition.pdf"); //PDF4NET v5: mctiFile.Close(); stm.Close(); }
public async Task CheckTest2() { var data = await TestUtils.GetFileAsBytes("test2.pdf"); var f = new dummyFile(); f.GetStream = () => { throw new InvalidOperationException(); }; // Install original data in cache var dc = new dummyCache(); await f.SaveFileInCache(f.DateToReturn, data, dc); // Create VM's and hook them up. var vm = new FileDownloadController(f, dc); var pf = new PDFFile(vm); var dummy1 = pf.NumberOfPages; // Start it off vm.DownloadOrUpdate.Execute(null); await pf.WhenAny(x => x.NumberOfPages, y => y.Value) .Where(y => y != 0) .Take(1) .Timeout(TimeSpan.FromSeconds(1), Observable.Return(0)) .FirstAsync(); Assert.AreEqual(6, pf.NumberOfPages); // Now, make sure that we still get a "1" out of the update guy. }
private bool CheckEncryption() { _encryptionLabel.Visible = true; Application.DoEvents(); bool success = false; using (WaitCursor wait = new WaitCursor()) { bool encrypted = PDFFile.IsEncrypted(_fileName); _encryptionValueLabel.Visible = true; _encryptionValueLabel.Text = encrypted ? DemosGlobalization.GetResxString(GetType(), "resx_Encrypted") : DemosGlobalization.GetResxString(GetType(), "resx_NotEncrypted"); Application.DoEvents(); if (encrypted) { using (GetPasswordDialog dlg = new GetPasswordDialog()) { if (dlg.ShowDialog(this) == DialogResult.OK) { success = true; _password = dlg.Password; } } } else { success = true; } } return success; }
public async Task MonitorPageUpdateEarlyRenderRequest() { // In this test we make sure not to access the # of pages. var f = new dummyFile(); var data = await TestUtils.GetFileAsBytes("test.pdf"); f.GetStream = () => { return(Observable.Return(new StreamReader(new MemoryStream(data)))); }; var dc = new dummyCache(); var vm = new FileDownloadController(f, dc); var pf = new PDFFile(vm); // Run the download (which will complete synchronously here), and then schedule the watch // for new items. vm.DownloadOrUpdate.Execute(null); var pupdate = await pf.GetPageStreamAndCacheInfo(5).Timeout(TimeSpan.FromSeconds(5)).FirstAsync(); // Make sure all that came back is ok. Assert.IsNotNull(pupdate); var page = await pupdate.Item2.FirstAsync(); Assert.AreEqual(5, (int)page.Index); }
public async Task WaitForFirstSlideAfterReady() { // Get the dummy file and input real PDF data. // Hook it up to the download controller var f = new dummyFile(); var data = await TestUtils.GetFileAsBytes("test.pdf"); f.GetStream = () => { return(Observable.Return(new StreamReader(new MemoryStream(data)))); }; var dc = new dummyCache(); var fdc = new FileDownloadController(f, dc); var pf = new PDFFile(fdc); var dummy1 = pf.NumberOfPages; // Run the download fdc.DownloadOrUpdate.Execute(null); await TestUtils.SpinWait(() => pf.NumberOfPages != 0, 1000); // The first spin guy var hero = new FirstSlideHeroViewModel(pf, null); // Make sure the thing is ready now. await TestUtils.SpinWait(() => hero.HeroPageUC != null, 1000); }
public async Task CheckCacheLookupHappensOnce() { // When we have an item that is cached, we shouldn't do the full load // too many times, (once) when looking at only the page number. var f = new dummyFile(); var data = await TestUtils.GetFileAsBytes("test.pdf"); f.GetStream = () => { throw new InvalidOperationException(); }; // Install original data in cache var dc = new dummyCache(); await f.SaveFileInCache(f.DateToReturn, data, dc); // Create VM's and hook them up. var vm = new FileDownloadController(f, dc); var pf = new PDFFile(vm); var dummy1 = pf.NumberOfPages; // Start it off vm.DownloadOrUpdate.Execute(null); await TestUtils.SpinWait(() => pf.NumberOfPages == 10, 1000); // Now, make sure we did it only once. // TODO: Currently this is 2 b.c. there is a second lookup for a date, which also includes // going after the file data. This should get fixed and split the database up. Assert.AreEqual(3, dc.NumberTimesGetCalled); }
private void _sourceFileNameBrowseButton_Click(object sender, EventArgs e) { bool isPostscript; PDFFile document = BrowsePDFDocument(false, out isPostscript); if (document != null) { _sourceDocument = document; _isSourcePostscript = isPostscript; _sourceFileNameTextBox.Text = _sourceDocument.FileName; if (!_isSourcePostscript) { _sourceFilePropertiesControl.Visible = true; _sourceFilePropertiesControl.SetFileProperties(_sourceDocument); _sourceDocumentPropertiesControl.Visible = true; _sourceDocumentPropertiesControl.SetDocumentProperties(_sourceDocument.DocumentProperties, true); _operationPageCountLabel.Text = string.Format("Document has {0} pages.", _sourceDocument.Pages.Count); _operationAllPagesCheckBox.Checked = true; _operationFirstPageNumberTextBox.Text = "1"; _operationLastPageNumberTextBox.Text = _sourceDocument.Pages.Count.ToString(); _sourceFileIsPostscriptLabel.Visible = false; } else { _sourceFilePropertiesControl.Visible = false; _sourceDocumentPropertiesControl.Visible = false; _sourceFileIsPostscriptLabel.Visible = true; } UpdateUIState(); } }
/// <summary> /// 将Pdf转换成图片存放在指定的文件夹下面并且返回转换了多少张图片(插件:O2S.Components.PDFRender4NETd) /// (使用:调用此方法传递参数,最后一个参数为模糊度(参考传递30)) /// </summary> /// <param name="pdfInputPath">源PDF路径</param> /// <param name="imageOutpPutPath">PDF转化成图片之后存放的路径</param> /// <param name="imageFormat">转换的图片格式</param> /// <param name="difinition">传递参数模糊度</param> /// <returns>返回转换了多少张图片信息</returns> public static int PdfConvertImageInfo(string pdfInputPath, string imageOutpPutPath, ImageFormat imageFormat, float difinition) { try { //第一步:判断需要转换的PDF是否存在 if (!File.Exists(pdfInputPath)) { throw new System.Exception("PDF的路径不存在"); } //第二步:判断存放转换后图片的地址是否存在 if (!Directory.Exists(imageOutpPutPath)) { throw new System.Exception("存放图片的路径不存在"); } //第三步:进行转换(使用插件O2S.Components.PDFRender4NET) PDFFile pdfFile = PDFFile.Open(pdfInputPath); int pageCount = pdfFile.PageCount; for (int i = 0; i < pageCount; i++) { Bitmap bitmap = pdfFile.GetPageImage(i, difinition); bitmap.Save(Path.Combine(imageOutpPutPath, i + "." + imageFormat), imageFormat); bitmap.Dispose(); } pdfFile.Dispose(); //第四步:返回PDF转换了多少张图片的个数 return(pageCount); } catch (System.Exception exception) { throw new System.Exception("PDF转换图片出现错误了,错误原因:" + exception.Message); } }
private void _destinationFileNameBrowseButton_Click(object sender, EventArgs e) { OperationItem operationItem = GetCurrentOperation(); if (operationItem.DestinationMustExist) { // Destination file must be a valid PDF file bool isPostscript; PDFFile destinationDocument = BrowsePDFDocument(true, out isPostscript); if (destinationDocument != null) { _destinationDocument = destinationDocument; _destinationFileNameTextBox.Text = _destinationDocument.FileName; _destinationFilePropertiesControl.SetFileProperties(_destinationDocument); } } else { // We will not check here string fileName = RunPDFSaveFileDialog(); if (fileName != null) { _destinationFileNameTextBox.Text = fileName; } } UpdateUIState(); }
public async Task ButtonNotGoodTillDownload() { // Build a PDF file that will only download after we ask it to. var f = new dummyFile(); var data = await TestUtils.GetFileAsBytes("test.pdf"); f.GetStream = () => { return(Observable.Return(new StreamReader(new MemoryStream(data)))); }; var dc = new dummyCache(); var vm = new FileDownloadController(f, dc); var pdf = new PDFFile(vm); // Open a single talk and see if we can see it open. var now = new TimePeriod(DateTime.Now, DateTime.Now + TimeSpan.FromSeconds(1000)); var exp = new ExpandingSlideThumbViewModel(pdf, now); // Make sure there are no slides - also primes the pump for Rx. Assert.IsNull(exp.TalkAsThumbs); await TestUtils.SpinWait(() => exp.CanShowThumbs == false, 1000); // Now, make sure that things go "true" after we fire off the file. vm.DownloadOrUpdate.Execute(null); await TestUtils.SpinWait(() => exp.CanShowThumbs == true, 1000); }
public ActionResult FileUploaderAjax(PDFFile membervalues) { //string FileName = Path.GetFileNameWithoutExtension(membervalues.PDFFileName.FileName); ////To Get File Extension //string FileExtension = Path.GetExtension(membervalues.PDFFileName.FileName); ////Add Current Date To Attached File Name //FileName = DateTime.Now.ToString("yyyyMMdd") + "-" + FileName.Trim() + FileExtension; string errorLogPathStr = ConfigurationManager.AppSettings["ErrorLogPath"]; string errorLogPath = Server.MapPath(errorLogPathStr); bool deleteUploadedFile; try { if (Request.Files.Count > 0) { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); string UploadPathConfig = ConfigurationManager.AppSettings["UploadPath"].ToString(); deleteUploadedFile = Convert.ToBoolean(ConfigurationManager.AppSettings["DeleteUploadedFile"].ToString()); string UploadPath = Server.MapPath(UploadPathConfig); var path = Path.Combine(UploadPath, fileName);//+"_"+Guid.NewGuid().ToString() if (!System.IO.File.Exists(path)) { file.SaveAs(path); } TextExtraction textExtraction = new TextExtraction(); Dictionary <string, Int64> keyValuePairs = textExtraction.CalculatePages(path, errorLogPath); ViewBag.PDFInfo = keyValuePairs; ViewBag.FilePath = path; if (deleteUploadedFile && System.IO.File.Exists(path)) { System.IO.File.Delete(path); } return(Json(new { Total = keyValuePairs["TotalPages"], Colored = keyValuePairs["ColorPages"], BlackAndWhite = keyValuePairs["BWPages"] }, JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { CreateLog(ex, errorLogPath); } //Get Upload path from Web.Config file AppSettings. //Its Create complete path to store in server. //membervalues.ImagePath = UploadPath + FileName; //To copy and save file into server. //membervalues.PDFFileName.SaveAs(membervalues.ImagePath); return(View()); }