public static void ExportVisualAsPdf(Visual visual) { SaveFileDialog saveFileDialog = new SaveFileDialog { DefaultExt = ".pdf", Filter = "PDF Documents (.pdf)|*.pdf" }; bool?result = saveFileDialog.ShowDialog(); if (result != true) { return; } using (MemoryStream memoryStream = new MemoryStream()) { System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream, FileMode.Create); XpsDocument xpsDocument = new XpsDocument(package); XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument); xpsDocumentWriter.Write(visual); xpsDocument.Close(); package.Close(); var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream); XpsConverter.Convert(pdfXpsDoc, saveFileDialog.FileName, 0); } }
public void TestCantFindUtilities() { var xpsFilePath = "Resources\\analysis.xps"; var exception = Assert.Throws <Win32Exception>(() => XpsConverter.Convert(xpsFilePath)); StringAssert.Contains($"The system cannot find the file specified.", exception.Message); }
public void TestXpsNotEmpty() { var utilitiesPath = "Utilities\\"; var exception = Assert.Throws <ArgumentNullException>(() => XpsConverter.Convert(string.Empty, utilitiesPath)); StringAssert.Contains("Xps file path can't be empty. Please, specify a valid xps file path.", exception.Message); }
public void TestPdfNotEmpty() { var xpsFilePath = "Resources\\tiger.xps"; var exception = Assert.Throws <ArgumentNullException>(() => XpsConverter.Convert(xpsFilePath, null)); StringAssert.Contains("Pdf file path can't be empty. Please, specify a valid pdf file path.", exception.Message); }
public void TestFailedToOpenXps() { var xpsFilePath = "Resources\\wrong.xps"; var exception = Assert.Throws <XpsConverterException>(() => XpsConverter.Convert(xpsFilePath)); StringAssert.Contains($"Failed to open file '{xpsFilePath}'", exception.Message); }
public void TestConvertWithXpsOnly() { var xpsFilePath = "Resources\\analysis.xps"; var pdfFilePath = "Resources\\analysis.pdf"; XpsConverter.Convert(xpsFilePath); Assert.That(pdfFilePath, Does.Exist); }
public void Convert1() { var testRootDir = TestContext.TestDeploymentDir; var xpsFile = Path.Combine(testRootDir, "XpsConverterTest/xps", "page1.xps"); var pdfFile = Path.ChangeExtension(xpsFile, ".pdf"); XpsConverter.Convert(xpsFile); Assert.IsTrue(File.Exists(pdfFile)); }
public void Convert2() { var testRootDir = TestContext.WorkDirectory; var xpsFile = Path.Combine(testRootDir, "XpsConverterTest/xps", "page1.xps"); var pdfFile = Path.Combine(testRootDir, "XpsConverterTest/xps", "page1_2.pdf"); XpsConverter.Convert(xpsFile, pdfFile, 0); Assert.IsTrue(File.Exists(pdfFile)); }
public void TestConvertFileWithSpacesInPath() { var xpsFilePath = "Resources\\file with spaces.xps"; var pdfFilePath = "Resources\\file with spaces.pdf"; XpsConverter.Convert(xpsFilePath); Assert.That(pdfFilePath, Does.Exist); }
public void TestConvertWithXpsAndPdf() { var xpsFilePath = "Resources\\tiger.xps"; var pdfFilePath = "Resources\\tiger.pdf"; XpsConverter.Convert(xpsFilePath, pdfFilePath); Assert.That(pdfFilePath, Does.Exist); }
public static void ExportVisualAsPdf(MainWindowViewModel usefulDataVM) { //Set up the WPF Control to be printed UserControl1 controlToPrint; controlToPrint = new UserControl1(); controlToPrint.DataContext = usefulDataVM; PageContent pageContent = new PageContent(); FixedPage fixedPage = new FixedPage(); fixedPage.Children.Add(controlToPrint); ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage); SaveFileDialog sfd = new SaveFileDialog { DefaultExt = ".pdf", Filter = "PDF Documents (.pdf)|*.pdf" }; bool?result = sfd.ShowDialog(); if (result != true) { return; } MemoryStream memoryStream = new MemoryStream(); System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream, FileMode.Create); XpsDocument xpsDocument = new XpsDocument(package); XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument); xpsDocumentWriter.Write(fixedPage); xpsDocument.Close(); package.Close(); var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream); //public static void Convert(Stream xpsInStream, Stream pdfOutStream, bool closePdfStream); XpsConverter.Convert(pdfXpsDoc, sfd.FileName, 0); Process.Start(sfd.FileName); }
public void TestHyperlink() { using (var xpsDoc = XpsDocument.Open("NavigateUri/Hyperlink.xps")) { PdfDocument pdfDocument = new PdfDocument(); XpsConverter converter = new XpsConverter(pdfDocument, xpsDoc); PdfPage pdfPage = converter.CreatePage(0); converter.RenderPage(pdfPage, 0); Assert.AreEqual(2, pdfPage.Annotations.Count); Assert.AreEqual(typeof(PdfLinkAnnotation), pdfPage.Annotations[0].GetType()); Assert.AreEqual(typeof(PdfLinkAnnotation), pdfPage.Annotations[1].GetType()); } }
private void CreateDocumentFile(string filepath, FlowDocument document) { const string temporaryFilePath = "tmp.xps"; DocumentPaginator paginator = (document as IDocumentPaginatorSource).DocumentPaginator; XpsDocument outputFile = new XpsDocument(temporaryFilePath, FileAccess.Write); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(outputFile); writer.Write(paginator); outputFile.Close(); XpsConverter.Convert(temporaryFilePath, filepath, 1); File.Delete(temporaryFilePath); Context.StopLoading(); }
#pragma warning restore CS0067 protected override JobState RunJobWork() { SetThreadName(); OutputFiles.Clear(); SetUpActions(); var converter = new XpsConverter(JobInfo); var path = Path.Combine(JobTempOutputFolder, JobTempFileName + Path.GetExtension(OutputFilenameTemplate)); converter.Convert(path); //PDFProcessor.process MoveOutputFile(path); JobState = JobState.Succeeded; return(JobState); }
public void ConvertManyInput() { var testRootDir = TestContext.WorkDirectory; var xps1File = Path.Combine(testRootDir, "XpsConverterTest/xps", "page1.xps"); var xps2File = Path.Combine(testRootDir, "XpsConverterTest/xps", "page2.xps"); var xps3File = Path.Combine(testRootDir, "XpsConverterTest/xps", "page3.xps"); var pdfFile = Path.Combine(testRootDir, "XpsConverterTest/xps", "page_123.pdf"); var pdfDoc = XpsConverter.Convert( XpsDocument.Open(xps1File).GetDocument().Pages .Concat(XpsDocument.Open(xps2File).GetDocument().Pages) .Concat(XpsDocument.Open(xps3File).GetDocument().Pages) ); Assert.AreEqual(3, pdfDoc.PageCount); pdfDoc.Save(pdfFile); Assert.IsTrue(File.Exists(pdfFile)); }
private static void PrintXpsAsPdf(string tempFile, string pdfFilename, List <Exception> exceptions) { try { XpsConverter.Convert(tempFile, pdfFilename, 0); Process.Start(pdfFilename); } catch (Exception e) { exceptions.Add(e); } try { File.Delete(tempFile); } catch (AccessViolationException access) { exceptions.Add(access); } }
public void Convert(System.Windows.Documents.FlowDocument document, Stream documentStream) { using (var xpsDocumentStream = new MemoryStream()) { using (var package = Package.Open(xpsDocumentStream, FileMode.Create, FileAccess.ReadWrite)) { using (var xpsDocument = new XpsDocument(package, CompressionOption.Maximum)) { var serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false); var paginator = ((IDocumentPaginatorSource)document).DocumentPaginator; serializer.SaveAsXaml(paginator); serializer.Commit(); } } xpsDocumentStream.Position = 0; XpsConverter.Convert(xpsDocumentStream, documentStream); } }
public static void ExportVisualAsPdf(Visual visual) { SaveFileDialog saveFileDialog = new SaveFileDialog { DefaultExt = ".pdf", Filter = "PDF Documents (.pdf)|*.pdf" }; bool?result = saveFileDialog.ShowDialog(); if (result != true) { return; } using (MemoryStream memoryStream = new MemoryStream()) { System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream, FileMode.OpenOrCreate); XpsDocument xpsDocument = new XpsDocument(package); XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument); xpsDocumentWriter.Write(visual); xpsDocument.Close(); var packageUri = new Uri("memorystream://myXps.xps"); PackageStore.AddPackage(packageUri, package); XpsDocument doc = new XpsDocument(package, CompressionOption.SuperFast, packageUri.AbsoluteUri); XpsConverter.Convert(doc, saveFileDialog.FileName, 0); package.Close(); //var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream); //XpsConverter.Convert(pdfXpsDoc, saveFileDialog.FileName, 0); } }
public void TestRenderingTypographySamples() { #if true string path = "PdfSharp/testing/SampleXpsDocuments_1_0/MXDW"; string dir = GetDirectory(path); if (dir == null) { throw new FileNotFoundException("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet."); } if (!Directory.Exists(dir)) { throw new FileNotFoundException("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet."); } string[] files = Directory.GetFiles(dir, "*Poster.xps", SearchOption.TopDirectoryOnly); if (files.Length == 0) { throw new Exception("No sample file found."); } foreach (string filename in files) { //if (!filename.EndsWith("CalibriPoster.xps")) // continue; Debug.WriteLine(filename); try { XpsDocument xpsDoc = XpsDocument.Open(filename); int docIndex = 0; foreach (FixedDocument doc in xpsDoc.Documents) { PdfDocument pdfDocument = new PdfDocument(); //PdfRenderer renderer = new PdfRenderer(); XpsConverter converter = new XpsConverter(pdfDocument, xpsDoc); int pageIndex = 0; foreach (FixedPage page in doc.Pages) { Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); // HACK: API is senseless PdfPage pdfPage = converter.CreatePage(pageIndex); converter.RenderPage(pdfPage, pageIndex); pageIndex++; } string pdfFilename = IOPath.GetFileNameWithoutExtension(filename); if (docIndex != 0) { pdfFilename += docIndex.ToString(); } pdfFilename += ".pdf"; pdfFilename = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename); pdfDocument.Save(pdfFilename); docIndex++; } } catch (Exception ex) { Debug.WriteLine(ex.Message); GetType(); } } #else //string data = "2.11592697149066,169.466971230985 7.31945717924454E-09,161.067961604689"; //TokenizerHelper helper = new TokenizerHelper(data); //string t = helper.NextTokenRequired(); //t = helper.NextTokenRequired(); //t = helper.NextTokenRequired(); //t = helper.NextTokenRequired(); string[] files = Directory.GetFiles("../../../../../testing/PdfSharp.Xps.UnitTests/Typography", "*.xps", SearchOption.AllDirectories); //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.10\OpenSource\PDFsharp\WPF\SampleXpsDocuments_1_0\FontPoster", "*.xps", SearchOption.AllDirectories); if (files.Length == 0) { throw new Exception("No sample file found."); } foreach (string filename in files) { // No negative tests here if (filename.Contains("\\ConformanceViolations\\")) { continue; } //if (!filename.EndsWith("CalibriPoster.xps")) // continue; Debug.WriteLine(filename); try { #if true XpsDocument xpsDoc = XpsDocument.Open(filename); int docIndex = 0; foreach (FixedDocument doc in xpsDoc.Documents) { PdfDocument pdfDocument = new PdfDocument(); //PdfRenderer renderer = new PdfRenderer(); XpsConverter converter = new XpsConverter(pdfDocument, xpsDoc); int pageIndex = 0; foreach (FixedPage page in doc.Pages) { Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); // HACK: API is senseless PdfPage pdfPage = converter.CreatePage(pageIndex); converter.RenderPage(pdfPage, pageIndex); pageIndex++; } string pdfFilename = IOPath.GetFileNameWithoutExtension(filename); if (docIndex != 0) { pdfFilename += docIndex.ToString(); } pdfFilename += ".pdf"; pdfFilename = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename); pdfDocument.Save(pdfFilename); docIndex++; } #else int docIndex = 0; XpsDocument xpsDoc = XpsDocument.Open(filename); foreach (FixedDocument doc in xpsDoc.Documents) { PdfDocument pdfDoc = new PdfDocument(); PdfRenderer renderer = new PdfRenderer(); int pageIndex = 0; foreach (FixedPage page in doc.Pages) { Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); PdfPage pdfPage = renderer.CreatePage(pdfDoc, page); renderer.RenderPage(pdfPage, page); pageIndex++; } string pdfFilename = IOPath.GetFileNameWithoutExtension(filename); if (docIndex != 0) { pdfFilename += docIndex.ToString(); } pdfFilename += ".pdf"; pdfFilename = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename); pdfDoc.Save(pdfFilename); docIndex++; } #endif } catch (Exception ex) { Debug.WriteLine(ex.Message); GetType(); } } #endif }
//enum Page //{ // Next = 0, // Back = 1 //} //private void otherPage(Page page) //{ // if (page == Page.Back) // { // if (index > 0) // index--; // else // index = tempPagesToShow.ToArray().Length - 1; // } // else if (page == Page.Next) // { // if (index < tempPagesToShow.ToArray().Length - 1) // index++; // else // index = 0; // } // openthisinviewer(index); //} //private void button_Left_Click(object sender, RoutedEventArgs e) //{ // otherPage(Page.Back); //} //private void button_Right_Click(object sender, RoutedEventArgs e) //{ // otherPage(Page.Next); //} public void PrintPDF() { PdfDocument output = new PdfDocument(); for (int i = 0; i < tempPagesToShow.Count(); i++) { FileStream fs = new FileStream(_pageurls[i],FileMode.Open); var pdfxpsdoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(fs); XpsConverter.Convert(pdfxpsdoc, pdfpath + _pagename[i] + ".pdf", 0); _pdfurls.Add(pdfpath + _pagename[i] + ".pdf"); //File.Copy(_pageurls[i], xpspath + "topdf" + (i + 1).ToString() + ".xps", true); //var pdfxpsdoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(xpspath + "topdf" + (i + 1).ToString() + ".xps"); //XpsConverter.Convert(pdfxpsdoc, pdfpath + _pagename[i] + ".pdf", 0); //_pdfurls.Add(pdfpath + _pagename[i] + ".pdf"); pdfxpsdoc.Close(); fs.Close(); } foreach (string _pdfurl in _pdfurls) { using (PdfDocument input = PdfSharp.Pdf.IO.PdfReader.Open(_pdfurl, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import)) { output.Version = input.Version; foreach (PdfPage page in input.Pages) { output.AddPage(page); } } System.IO.FileInfo oldpdf = new System.IO.FileInfo(_pdfurl); oldpdf.Delete(); } System.IO.FileInfo[] files = new System.IO.DirectoryInfo(pdfpath).GetFiles("*" + pdfoutname + "*.pdf"); string outputpath = ""; if (files.Length > 0 && saveas) { outputpath = pdfpath + pdfoutname + "_" + files.Length + ".pdf"; } else { outputpath = pdfpath + pdfoutname + ".pdf"; } output.Save(outputpath); output.Dispose(); //System.IO.FileInfo info = new System.IO.FileInfo(outputpath); /////pdfFileSize << 요놈 //long pdfFileSize = info.Length; //Rhino.RhinoApp.WriteLine(pdfoutname + "size = " + pdfFileSize.ToString() + "bytes"); ///서버업로드용 path 등록 /// var dictionaryTempIndex = TuringAndCorbusierPlugIn.InstanceClass.turing.MainPanel_reportspaths[TuringAndCorbusierPlugIn.InstanceClass.turing.tempIndex]; if (dictionaryTempIndex.ContainsKey("REPORT") == true) { var result = MessageBox.Show("이미 등록된 설계 보고서가 있습니다. 새 보고서를 서버에 저장하시겠습니까?", "설계 보고서 덮어쓰기", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { dictionaryTempIndex.Remove("REPORT"); dictionaryTempIndex.Add("REPORT", outputpath); Rhino.RhinoApp.WriteLine("덮어쓰기 완료" + Environment.NewLine + "파일 경로 = " + outputpath); } } else { dictionaryTempIndex.Add("REPORT", outputpath); Rhino.RhinoApp.WriteLine("등록 완료" + Environment.NewLine + "파일 경로 = " + outputpath); } //var result = MessageBox.Show("출력 끝 파일열기 / 경로열기 / 닫기 ", "PDF로 보고서 출력", MessageBoxButton.YesNoCancel); //if (result == MessageBoxResult.Yes) //{ // System.Diagnostics.Process ps = new System.Diagnostics.Process(); // ps.StartInfo.FileName = pdfoutname + ".pdf"; // ps.StartInfo.WorkingDirectory = pdfpath; // ps.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; // ps.Start(); //} //else if (result == MessageBoxResult.No) //{ // System.Diagnostics.Process.Start("explorer.exe", pdfpath); //} this.documentViewer.Document = null; //System.IO.File.OpenRead(outputpath); //foreach (string xpss in _pageurls) //{ // System.IO.File.Delete(xpss); //} //foreach (string pdfs in _pdfurls) //{ // System.IO.File.Delete(pdfs); //} //UIManager.getInstance().HideWindow(TuringAndCorbusierPlugIn.InstanceClass.showmewindow, UIManager.WindowType.Print); string filename = ""; dictionaryTempIndex.TryGetValue("REPORT",out filename); System.Diagnostics.Process ps = new System.Diagnostics.Process(); ps.StartInfo.WorkingDirectory = pdfpath; ps.StartInfo.FileName = filename.Replace(pdfpath, ""); //MessageBox.Show(ps.StartInfo.FileName); ps.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; ps.EnableRaisingEvents = true; ps.Start(); return; Close(); //MessageBox.Show(tempPagesToShow[index].ActualHeight.ToString() + " , " + tempPagesToShow[index].Height.ToString()); }
public void QualityLogicMinBar() { // Download from http://www.microsoft.com/whdc/xps/xpssampdoc.mspx string path = "SampleXpsDocuments_1_0/QualityLogicMinBar"; string dir = (path); if (dir == null) { Assert.Inconclusive("Path not found: " + path); return; } if (!Directory.Exists(dir)) { Assert.Inconclusive("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet."); return; } string[] files = Directory.GetFiles(dir, "*.xps", SearchOption.AllDirectories); foreach (string filename in files) { //if (!filename.EndsWith("mb01.xps")) // continue; //if (filename.EndsWith("mb01.xps")) // continue; if (filename.EndsWith("mb02.xps")) { continue; } if (filename.EndsWith("mb03.xps")) { continue; } if (filename.EndsWith("mb04.xps")) { continue; } if (filename.EndsWith("mb05.xps")) { continue; } if (filename.EndsWith("mb06.xps")) { continue; } if (filename.EndsWith("mb07.xps")) { continue; } if (filename.EndsWith("mb08.xps")) { continue; } if (filename.EndsWith("mb09.xps")) { continue; } Debug.WriteLine(filename); try { XpsConverter.Convert(filename); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } }
public void TestRegressionByRasterization() { string dir = TestContext.WorkDirectory; Directory.CreateDirectory(Path.Combine(dir, "pdf")); Directory.CreateDirectory(Path.Combine(dir, "png")); string pdftoppm = Path.Combine(dir, "tools/win32/pdftoppm.exe"); string[] xpsFiles = Directory.GetFiles(dir, "xps/*.xps"); if (xpsFiles.Length == 0) { Assert.Inconclusive("No sample file found!"); return; } foreach (string xpsFile in xpsFiles) { Debug.WriteLine(xpsFile); string pdfFile = Path.Combine( Path.GetDirectoryName( Path.GetDirectoryName(xpsFile) ), "pdf", Path.GetFileNameWithoutExtension(xpsFile) + ".pdf" ); XpsConverter.Convert(xpsFile, pdfFile, 0); string pngPrefix = Path.Combine( Path.GetDirectoryName( Path.GetDirectoryName(xpsFile) ), "png", Path.GetFileNameWithoutExtension(xpsFile) ); ProcessStartInfo psi = new ProcessStartInfo( pdftoppm, $"-png -r 150 \"{pdfFile}\" \"{pngPrefix}\"" ); psi.UseShellExecute = false; Process process = Process.Start( psi ); process.WaitForExit(); } string pngDir = Path.Combine(dir, "png"); var hash = new SHA512Managed(); foreach (string pngFile in Directory.GetFiles(pngDir)) { string pngRefFile = Path.Combine( Path.GetDirectoryName( Path.GetDirectoryName(pngFile) ), "png-reference", Path.GetFileName(pngFile) ); string hashConverted = BitConverter.ToString( hash.ComputeHash(File.ReadAllBytes(pngFile)) ); string hashReference = BitConverter.ToString( hash.ComputeHash(File.ReadAllBytes(pngRefFile)) ); Assert.AreEqual(hashReference, hashConverted, $"{Path.GetFileNameWithoutExtension(pngFile)} differs!" ); } }
/// <summary> /// Divides elements of reportContainer into pages and exports them as PDF /// </summary> /// <param name="reportContainer">StackPanel containing report elements</param> /// <param name="dataContext">Data Context used in the report</param> /// <param name="margin">Margin of a report page</param> /// <param name="orientation">Landscape or Portrait orientation</param> /// <param name="resourceDictionary">Resources used in report</param> /// <param name="backgroundBrush">Brush that will be used as background for report page</param> /// <param name="reportHeaderDataTemplate"> /// Optional header for each page /// Note: You can use DynamicResource PageNumber in this template to display page number /// </param> /// <param name="headerOnlyOnTheFirstPage">Use header only on the first page (default is false)</param> /// <param name="reportFooterDataTemplate"> /// Optional footer for each page /// Note: You can use DynamicResource PageNumber in this template to display page number /// </param> /// <param name="footerStartsFromTheSecondPage">Do not use footer on the first page (default is false)</param> /// <param name="direction">Document Flow Direction</param> public static void ExportReportAsPdf( StackPanel reportContainer, object dataContext, Thickness margin, ReportOrientation orientation, ResourceDictionary resourceDictionary = null, Brush backgroundBrush = null, DataTemplate reportHeaderDataTemplate = null, bool headerOnlyOnTheFirstPage = false, DataTemplate reportFooterDataTemplate = null, bool footerStartsFromTheSecondPage = false, FlowDirection direction = FlowDirection.LeftToRight) { SaveFileDialog saveFileDialog = new SaveFileDialog { DefaultExt = ".pdf", Filter = "PDF Documents (.pdf)|*.pdf" }; bool?result = saveFileDialog.ShowDialog(); if (result != true) { return; } Size reportSize = GetReportSize(reportContainer, margin, orientation); List <FrameworkElement> ReportElements = new List <FrameworkElement>(reportContainer.Children.Cast <FrameworkElement>()); reportContainer.Children.Clear(); //to avoid exception "Specified element is already the logical child of another element." List <ReportPage> ReportPages = GetReportPages( resourceDictionary, backgroundBrush, ReportElements, dataContext, margin, reportSize, reportHeaderDataTemplate, headerOnlyOnTheFirstPage, reportFooterDataTemplate, footerStartsFromTheSecondPage); FixedDocument fixedDocument = new FixedDocument(); try { using (MemoryStream memoryStream = new MemoryStream()) { System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream, FileMode.Create); XpsDocument xpsDocument = new XpsDocument(package); XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument); foreach (Grid reportPage in ReportPages.Select(reportPage => reportPage.LayoutRoot)) { reportPage.Width = reportPage.ActualWidth; reportPage.Height = reportPage.ActualHeight; reportPage.FlowDirection = direction; FixedPage newFixedPage = new FixedPage(); newFixedPage.Children.Add(reportPage); newFixedPage.Measure(reportSize); newFixedPage.Arrange(new Rect(reportSize)); newFixedPage.Width = newFixedPage.ActualWidth; newFixedPage.Height = newFixedPage.ActualHeight; newFixedPage.Background = backgroundBrush; newFixedPage.UpdateLayout(); newFixedPage.FlowDirection = direction; PageContent pageContent = new PageContent(); pageContent.FlowDirection = direction; ((IAddChild)pageContent).AddChild(newFixedPage); fixedDocument.Pages.Add(pageContent); } xpsDocumentWriter.Write(fixedDocument); xpsDocument.Close(); var packageUri = new Uri("memorystream://myXps.xps"); PackageStore.AddPackage(packageUri, package); XpsDocument doc = new XpsDocument(package, CompressionOption.SuperFast, packageUri.AbsoluteUri); XpsConverter.Convert(doc, saveFileDialog.FileName, 0); package.Close(); //var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream); //XpsConverter.Convert(pdfXpsDoc, saveFileDialog.FileName, 0); } } finally { ReportPages.ForEach(reportPage => reportPage.ClearChildren()); ReportElements.ForEach(elm => reportContainer.Children.Add(elm)); reportContainer.UpdateLayout(); } }
public void TestRenderingTypographySamples() { #if true string path = "PdfSharp/testing/SampleXpsDocuments_1_0/MXDW"; string dir = GetDirectory(path); if (dir == null) throw new FileNotFoundException("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet."); if (!Directory.Exists(dir)) throw new FileNotFoundException("Path not found: " + path + ". Follow instructions in ../../../SampleXpsDocuments_1_0/!readme.txt to download samples from the Internet."); string[] files = Directory.GetFiles(dir, "*Poster.xps", SearchOption.TopDirectoryOnly); if (files.Length == 0) throw new Exception("No sample file found."); foreach (string filename in files) { //if (!filename.EndsWith("CalibriPoster.xps")) // continue; Debug.WriteLine(filename); try { XpsDocument xpsDoc = XpsDocument.Open(filename); int docIndex = 0; foreach (FixedDocument doc in xpsDoc.Documents) { PdfDocument pdfDocument = new PdfDocument(); //PdfRenderer renderer = new PdfRenderer(); XpsConverter converter = new XpsConverter(pdfDocument, xpsDoc); int pageIndex = 0; foreach (FixedPage page in doc.Pages) { Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); // HACK: API is senseless PdfPage pdfPage = converter.CreatePage(pageIndex); converter.RenderPage(pdfPage, pageIndex); pageIndex++; } string pdfFilename = IOPath.GetFileNameWithoutExtension(filename); if (docIndex != 0) pdfFilename += docIndex.ToString(); pdfFilename += ".pdf"; pdfFilename = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename); pdfDocument.Save(pdfFilename); docIndex++; } } catch (Exception ex) { Debug.WriteLine(ex.Message); GetType(); } } #else //string data = "2.11592697149066,169.466971230985 7.31945717924454E-09,161.067961604689"; //TokenizerHelper helper = new TokenizerHelper(data); //string t = helper.NextTokenRequired(); //t = helper.NextTokenRequired(); //t = helper.NextTokenRequired(); //t = helper.NextTokenRequired(); string[] files = Directory.GetFiles("../../../../../testing/PdfSharp.Xps.UnitTests/Typography", "*.xps", SearchOption.AllDirectories); //files = Directory.GetFiles(@"G:\!StLa\PDFsharp-1.10\OpenSource\PDFsharp\WPF\SampleXpsDocuments_1_0\FontPoster", "*.xps", SearchOption.AllDirectories); if (files.Length == 0) throw new Exception("No sample file found."); foreach (string filename in files) { // No negative tests here if (filename.Contains("\\ConformanceViolations\\")) continue; //if (!filename.EndsWith("CalibriPoster.xps")) // continue; Debug.WriteLine(filename); try { #if true XpsDocument xpsDoc = XpsDocument.Open(filename); int docIndex = 0; foreach (FixedDocument doc in xpsDoc.Documents) { PdfDocument pdfDocument = new PdfDocument(); //PdfRenderer renderer = new PdfRenderer(); XpsConverter converter = new XpsConverter(pdfDocument, xpsDoc); int pageIndex = 0; foreach (FixedPage page in doc.Pages) { Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); // HACK: API is senseless PdfPage pdfPage = converter.CreatePage(pageIndex); converter.RenderPage(pdfPage, pageIndex); pageIndex++; } string pdfFilename = IOPath.GetFileNameWithoutExtension(filename); if (docIndex != 0) pdfFilename += docIndex.ToString(); pdfFilename += ".pdf"; pdfFilename = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename); pdfDocument.Save(pdfFilename); docIndex++; } #else int docIndex = 0; XpsDocument xpsDoc = XpsDocument.Open(filename); foreach (FixedDocument doc in xpsDoc.Documents) { PdfDocument pdfDoc = new PdfDocument(); PdfRenderer renderer = new PdfRenderer(); int pageIndex = 0; foreach (FixedPage page in doc.Pages) { Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); PdfPage pdfPage = renderer.CreatePage(pdfDoc, page); renderer.RenderPage(pdfPage, page); pageIndex++; } string pdfFilename = IOPath.GetFileNameWithoutExtension(filename); if (docIndex != 0) pdfFilename += docIndex.ToString(); pdfFilename += ".pdf"; pdfFilename = IOPath.Combine(IOPath.GetDirectoryName(filename), pdfFilename); pdfDoc.Save(pdfFilename); docIndex++; } #endif } catch (Exception ex) { Debug.WriteLine(ex.Message); GetType(); } } #endif }
private void Button_Click_1(object sender, RoutedEventArgs e) { var dialog = new SaveFileDialog(); //dialog.AddExtension = true; dialog.DefaultExt = "pdf"; dialog.Filter = "PDF Document (*.pdf)|*.pdf"; if (dialog.ShowDialog() == false) { return; } #region Shrinks the uI Properly //align the page properly table1.Margin = new Thickness(-13, 116, 0, -16); //Height="647" Margin="-15,91,0,0" header1.Margin = new Thickness(7, 17, 12, 570); #endregion FixedDocument fixedDoc = new FixedDocument(); PageContent pageContent = new PageContent(); FixedPage fixedPage = new FixedPage(); #region This Flips the Paper (A4 by standard ro be landscape) fixedPage.Width = 11.6 * 96; fixedPage.Height = 8.27 * 96; #endregion //PrintDialog printDlg = new PrintDialog(); //Size pageSize = new Size(printDlg.PrintableAreaWidth, printDlg.PrintableAreaHeight - 100); UIElement visual = ((Panel)Content).Children[0] as UIElement; UIElement visual1 = ((Panel)Content).Children[1] as UIElement; ((Panel)Content).Children.Remove(visual); ((Panel)Content).Children.Remove(visual1); fixedPage.Children.Add(visual); fixedPage.Children.Add(visual1); ((IAddChild)pageContent).AddChild(fixedPage); fixedDoc.Pages.Add(pageContent); // write to PDF file string tempFilename = "temp.xps"; File.Delete(tempFilename); XpsDocument xpsd = new XpsDocument(tempFilename, FileAccess.Write); XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd); xw.Write(fixedDoc); xpsd.Close(); try { XpsConverter.Convert(tempFilename, dialog.FileName, 1); } catch (Exception) { MessageBox.Show("File To be Replaced is used by Another Application \n Try Closing the File and Try Again"); } finally { fixedPage.Children.Remove(visual); fixedPage.Children.Remove(visual1); ((Panel)Content).Children.Add(visual1); ((Panel)Content).Children.Add(visual); header1.Margin = new Thickness(5); table1.Margin = new Thickness(51, 38, 0, 0); } }