Ejemplo n.º 1
0
        private void DrawPage(IEnumerable <LabelContent> labelContents, SKDocument doc)
        {
            using var canvas = doc.BeginPage(this._layoutProperty.PageWidth, this._layoutProperty.PageHeight);

            var count = 0;

            for (int row = 0; row < this._layoutProperty.LabelRowCount; row++)
            {
                for (int column = 0; column < this._layoutProperty.LabelColumnCount; column++)
                {
                    if (count >= labelContents.Count())
                    {
                        break;
                    }

                    var content = labelContents.ElementAt(count);

                    this.DrawLabel(
                        content,
                        canvas,
                        this._layoutProperty.Margin + column * this._layoutProperty.UnitSize.Width,
                        this._layoutProperty.Margin + row * this._layoutProperty.UnitSize.Height);

                    count++;
                }
            }

            if (this._pdfContext.IsVisibleSeparateLine)
            {
                this.DrawSeparateLine(canvas);
            }

            doc.EndPage();
        }
Ejemplo n.º 2
0
 private void Add(SKDocument pdf, IPageContainer container)
 {
     using (var canvas = pdf.BeginPage((float)container.Template.Width, (float)container.Template.Height))
     {
         _presenter.Render(canvas, _renderer, container, 0, 0);
     }
 }
        public IActionResult Example1()
        {
            using (var ms = new MemoryStream())
                using (var stream = new SKManagedWStream(ms))
                    using (var document = SKDocument.CreatePdf(stream))
                    {
                        using (var canvas = document.BeginPage(595f, 847f))
                        {
                            using (var paint = new SKPaint())
                            {
                                paint.Color = SKColors.Black;

                                canvas.DrawLine(0, 0, 595f, 847f, paint);

                                paint.TextSize = 36;
                                canvas.DrawText("あいう36", 0, 0 + 36, paint);

                                canvas.DrawBitmap(CreateQrBitmap("https://localhost", 240, 240), 240, 0, paint);
                            }

                            document.EndPage();
                        }

                        document.Close();

                        return(File(ms.ToArray(), "application/pdf", "example1.pdf"));
                    }
        }
Ejemplo n.º 4
0
        private void Add(SKDocument pdf, XContainer container)
        {
            float width  = (float)container.Template.Width;
            float height = (float)container.Template.Height;

            using (SKCanvas canvas = pdf.BeginPage(width, height))
            {
                // Calculate x and y page scale factors.
                double scaleX = width / container.Template.Width;
                double scaleY = height / container.Template.Height;
                double scale  = Math.Min(scaleX, scaleY);

                // Set scaling function.
                _scaleToPage = (value) => (float)(value * scale);

                // Draw container template contents to pdf graphics.
                if (container.Template.Background.A > 0)
                {
                    DrawBackgroundInternal(
                        canvas,
                        container.Template.Background,
                        Rect2.Create(0, 0, width / scale, height / scale));
                }

                // Draw template contents to pdf graphics.
                Draw(canvas, container.Template, container.Data.Properties, container.Data.Record);

                // Draw page contents to pdf graphics.
                Draw(canvas, container, container.Data.Properties, container.Data.Record);
            }
        }
Ejemplo n.º 5
0
        public void CanCreatePdfWithMetadata()
        {
            var metadata = SKDocumentPdfMetadata.Default;

            metadata.Author = "SkiaSharp Team";

            using (var stream = new MemoryStream())
            {
                using (var doc = SKDocument.CreatePdf(stream, metadata))
                {
                    Assert.NotNull(doc);
                    Assert.NotNull(doc.BeginPage(100, 100));

                    doc.EndPage();
                    doc.Close();
                }

                Assert.True(stream.Length > 0);
                Assert.True(stream.Position > 0);

                stream.Position = 0;
                using (var reader = new StreamReader(stream))
                {
                    var contents = reader.ReadToEnd();
                    Assert.Contains("/Author (SkiaSharp Team)", contents);
                }
            }
        }
Ejemplo n.º 6
0
        public void CanCreateXps()
        {
            // XPS is only supported on Windows

            using (var stream = new MemoryStream())
            {
                using (new SKAutoCoInitialize())
                    using (var doc = SKDocument.CreateXps(stream))
                    {
                        if (IsWindows)
                        {
                            Assert.NotNull(doc);
                            Assert.NotNull(doc.BeginPage(100, 100));

                            doc.EndPage();
                            doc.Close();
                        }
                        else
                        {
                            Assert.Null(doc);
                        }
                    }

                if (IsWindows)
                {
                    Assert.True(stream.Length > 0);
                    Assert.True(stream.Position > 0);
                }
                else
                {
                    Assert.True(stream.Length == 0);
                    Assert.True(stream.Position == 0);
                }
            }
        }
Ejemplo n.º 7
0
        private void SkiaCreatePdf()
        {
            float width  = 800f;
            float height = 600f;

            using (var stream = new SKFileWStream("document.pdf"))
            {
                using (var document = SKDocument.CreatePdf(stream))
                {
                    // the first page
                    using (var canvas = document.BeginPage(width, height))
                    {
                        using (var paint = new SKPaint())
                        {
                            canvas.DrawText("...PDF...", 10f, 100f, paint);
                            document.EndPage();
                        }
                    }

                    // the second page
                    using (var canvas = document.BeginPage(width, height))
                    {
                        using (var paint = new SKPaint())
                        {
                            canvas.DrawText("...PDF...", 10f, 100f, paint);
                            document.EndPage();
                        }
                    }

                    // all done
                    document.Close();
                }
            }
        }
Ejemplo n.º 8
0
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            using (var stream = new MemoryStream())
            {
                using (var package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite))
                {
                    //using (var xpsDoc = new XpsDocument(package, CompressionOption.Maximum))
                    //{
                    //    var rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    //    var paginator = ((IDocumentPaginatorSource)DocViewer.Document).DocumentPaginator;
                    //    rsm.SaveAsXaml(paginator);
                    //    rsm.Commit();
                    //}


                    var pd = new PrintDialog();
                    if (pd.ShowDialog() == true)
                    {
                        //var tdoc = new XpsDocument(@"<SOMEPATH>\temp.xps", FileAccess.ReadWrite);
                        // var tdoc = new XpsDocument(package);
                        pd.PrintDocument(((IDocumentPaginatorSource)DocViewer.Document).DocumentPaginator, "temp.xps");
                    }
                }
                stream.Position = 0;

                var skdXpsDoc = SKDocument.CreateXps(stream);
            }
        }
Ejemplo n.º 9
0
        private void SaveToStream(SKWStream stream)
        {
            var metadata = new SKDocumentPdfMetadata
            {
                Author   = Author,
                Creation = DateTime.Now,
                Creator  = Creator,
                Keywords = Keywords,
                Modified = DateTime.Now,
                Producer = Producer,
                Subject  = Subject,
                Title    = Title,
            };

            int dpi = 72;

            using (var document = SKDocument.CreatePdf(stream, metadata, dpi))
            {
                foreach (var page in Pages)
                {
                    var pdfCanvas = document.BeginPage(page.Width, page.Height, page.Dimensions.GetContentRect().ToSKRect());

                    var pageRenderer = new PageRenderer(page);
                    pageRenderer.Render(pdfCanvas);

                    document.EndPage();
                }

                // end the doc
                document.Close();
            }
        }
        /// <summary>
        /// Encode output image as PDF
        /// </summary>
        /// <param name="surface"></param>
        /// <param name="width">Requested output width (pixels)</param>
        /// <param name="height">Requested output height (pixels)</param>
        /// <param name="q">Image quality (percentage)</param>
        /// <param name="pdfMetadata">Optional metadata to include in the PDF</param>
        /// <returns></returns>
        public static Stream EncodePdf(SKSurface surface, int width, int height, int q, Conf.PdfMetadata pdfMetadata)
        {
            // have to encode to JPEG then paint the encoded bytes, otherwise you get full JP2 quality
            var output = new MemoryStream();

            var metadata = new SKDocumentPdfMetadata()
            {
                Creation = DateTime.Now,
            };

            if (null != pdfMetadata)
            {
                metadata.Author = pdfMetadata.Author;
            }

            using (var skstream = new SKManagedWStream(output))
                using (var writer = SKDocument.CreatePdf(skstream, metadata))
                    using (var snapshot = surface.Snapshot())
                        using (var data = snapshot.Encode(SKEncodedImageFormat.Jpeg, q))
                            using (var image = SKImage.FromEncodedData(data))
                                using (var paint = new SKPaint())
                                {
                                    using (var canvas = writer.BeginPage(width, height))
                                    {
                                        paint.FilterQuality = SKFilterQuality.High;
                                        canvas.DrawImage(image, new SKRect(0, 0, width, height), paint);
                                        writer.EndPage();
                                    }
                                }
            output.Seek(0, SeekOrigin.Begin);
            return(output);
        }
        public void CanCreateXps()
        {
            // XPS is only supported on Windows

            using (var stream = new MemoryStream())
                using (var managed = new SKManagedWStream(stream, false))
                {
                    using (var doc = SKDocument.CreateXps(managed))
                    {
                        if (IsWindows)
                        {
                            Assert.IsNotNull(doc);
                            Assert.IsNotNull(doc.BeginPage(100, 100));

                            doc.EndPage();
                            doc.Close();
                        }
                        else
                        {
                            Assert.IsNull(doc);
                        }
                    }

                    if (IsWindows)
                    {
                        Assert.IsTrue(stream.Length > 0);
                        Assert.IsTrue(stream.Position > 0);
                    }
                    else
                    {
                        Assert.IsTrue(stream.Length == 0);
                        Assert.IsTrue(stream.Position == 0);
                    }
                }
        }
Ejemplo n.º 12
0
            static SKDocument CreateDocument(out IntPtr streamHandle)
            {
                var stream = new SKDynamicMemoryWStream();

                streamHandle = stream.Handle;

                return(SKDocument.CreatePdf(stream, new SKDocumentPdfMetadata()));
            }
Ejemplo n.º 13
0
 public static void Render(Control target, Size size, Stream stream, double dpi = 72, bool useDeferredRenderer = false)
 {
     using var managedWStream = new SKManagedWStream(stream);
     using var document       = SKDocument.CreateXps(stream, (float)dpi);
     using var canvas         = document.BeginPage((float)size.Width, (float)size.Height);
     target.Measure(size);
     target.Arrange(new Rect(size));
     CanvasRenderer.Render(target, canvas, dpi, useDeferredRenderer);
 }
Ejemplo n.º 14
0
 internal static void ExportXps(IToolContext context, string path, IContainerView containerView)
 {
     using var stream = new SKFileWStream(path);
     using var xps    = SKDocument.CreateXps(stream, SKDocument.DefaultRasterDpi);
     using var canvas = xps.BeginPage((float)containerView.Width, (float)containerView.Height);
     using var skiaContainerPresenter = new SkiaExportContainerPresenter(context, containerView);
     skiaContainerPresenter.Draw(canvas, containerView.Width, containerView.Height, 0, 0, 1.0, 1.0);
     xps.Close();
 }
Ejemplo n.º 15
0
 public void Save(Stream stream, DocumentContainerViewModel document)
 {
     using var pdf = SKDocument.CreatePdf(stream, _targetDpi);
     foreach (var container in document.Pages)
     {
         Add(pdf, container);
     }
     pdf.Close();
     _renderer.ClearCache();
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates a PDF document displaying the given identity as QR code and text and
        /// providing some guidance for the user.
        /// </summary>
        /// <param name="fileName">The full file name (including the path) for the document.</param>
        /// <param name="identity">The identity for which to create the document.</param>
        /// <param name="blockTypes">Spciefies a list of block types to include.</param>
        public static void CreateIdentityDocument(string fileName, SQRLIdentity identity, List <ushort> blockTypes)
        {
            if (string.IsNullOrEmpty(fileName) ||
                identity == null ||
                blockTypes == null ||
                blockTypes.Count < 1)
            {
                throw new ArgumentException(string.Format("{0}, {1} and {2} must be specified and valid!",
                                                          nameof(fileName), nameof(identity), nameof(blockTypes)));
            }

            _pageNr = 0;
            string title = "\"" + identity.IdentityName + "\" " + _loc.GetLocalizationValue("FileDialogFilterName");
            string identityEncryptionMessage = blockTypes.Contains(1) ?
                                               _loc.GetLocalizationValue("IdentityDocEncMsgPassword") :
                                               _loc.GetLocalizationValue("IdentityDocEncMsgRC");
            string textualIdentityMessage = _loc.GetLocalizationValue("IdentityDocumentTextualIdentityMessage");
            string guidanceMessage        = _loc.GetLocalizationValue("IdentityDocumentGuidanceMessage");
            var    identityBytes          = identity.ToByteArray(includeHeader: true, blockTypes);
            string textualIdentity        = SQRL.GenerateTextualIdentityBase56(identityBytes);

            var metadata = new SKDocumentPdfMetadata
            {
                Author          = _assemblyName,
                Creation        = DateTime.Now,
                Creator         = _assemblyName,
                Keywords        = "SQRL,Identity",
                Modified        = DateTime.Now,
                Producer        = "SkiaSharp",
                Subject         = "SQRL Identity Document",
                Title           = "SQRL Identity Document",
                EncodingQuality = 300,
                RasterDpi       = 300
            };

            using (SKBitmap qrCode = CreateQRCode(identityBytes))
                using (var stream = new SKFileWStream(fileName))
                    using (_document = SKDocument.CreatePdf(stream, metadata))
                    {
                        StartNextPage();

                        float qrCodeWidth  = (qrCode.Width <= QRCODE_MAX_SIZE) ? qrCode.Width : QRCODE_MAX_SIZE;
                        float qrCodeHeight = (qrCode.Height <= QRCODE_MAX_SIZE) ? qrCode.Height : QRCODE_MAX_SIZE;

                        DrawTextBlock(title, _fontBold, 23, SKColors.Black, 10f);
                        DrawTextBlock(identityEncryptionMessage, _fontRegular, 12, SKColors.DarkGray, -5f, SKTextAlign.Left, 1.3f);
                        DrawBitmap(qrCode, SKTextAlign.Center, qrCodeWidth, qrCodeHeight, 15f);
                        DrawTextBlock(textualIdentityMessage, _fontRegular, 12, SKColors.DarkGray, 10f, SKTextAlign.Left, 1.3f);
                        DrawTextBlock(textualIdentity, _fontMonoBold, 12, SKColors.Black, 15f, SKTextAlign.Center, 1.3f);;
                        DrawTextBlock(guidanceMessage, _fontRegular, 12, SKColors.DarkGray, 0f, SKTextAlign.Left, 1.3f);

                        EndPage();
                        _document.Close();
                    }
        }
Ejemplo n.º 17
0
        public unsafe void StreamIsNotDisposedWhenReferencedIsDisposed()
        {
            var stream = new SKManagedWStream(new MemoryStream(), true);
            var handle = stream.Handle;

            var document = SKDocument.CreatePdf(stream);

            document.Dispose();

            Assert.True(SKObject.GetInstance <SKManagedWStream>(handle, out _));
        }
Ejemplo n.º 18
0
 /// <inheritdoc/>
 void IProjectExporter.Save(string path, IPageContainer container)
 {
     using (var stream = new SKFileWStream(path))
     {
         using (var pdf = SKDocument.CreatePdf(stream, _targetDpi))
         {
             Add(pdf, container);
             pdf.Close();
         }
     }
 }
Ejemplo n.º 19
0
 internal static void ExportPdf(IToolContext context, string path, IContainerView containerView)
 {
     using (var stream = new SKFileWStream(path))
         using (var pdf = SKDocument.CreatePdf(stream, SKDocument.DefaultRasterDpi))
             using (var canvas = pdf.BeginPage((float)containerView.Width, (float)containerView.Height))
                 using (var skiaContainerPresenter = new SkiaExportContainerPresenter(context, containerView))
                 {
                     skiaContainerPresenter.Draw(canvas, containerView.Width, containerView.Height, 0, 0, 1.0, 1.0);
                     pdf.Close();
                 }
 }
Ejemplo n.º 20
0
        /// <inheritdoc/>
        public void Export(IPlotModel model, Stream stream)
        {
            using var document  = SKDocument.CreatePdf(stream);
            using var pdfCanvas = document.BeginPage(this.Width, this.Height);
            using var context   = new SkiaRenderContext { RenderTarget = RenderTarget.VectorGraphic, SkCanvas = pdfCanvas, UseTextShaping = this.UseTextShaping };
            const float dpiScale = 72f / 96;

            context.DpiScale = dpiScale;
            model.Update(true);
            pdfCanvas.Clear(model.Background.ToSKColor());
            model.Render(context, new OxyRect(0, 0, this.Width / dpiScale, this.Height / dpiScale));
        }
Ejemplo n.º 21
0
        public void TestCreate()
        {
            var idx = SKIndex.CreateWithUrl(new NSUrl("file://" + path), "myIndex", SKIndexType.InvertedVector, null);

            if (idx == null)
            {
                throw new Exception();
            }


            var d1 = new SKDocument(new NSUrl("file:///etc/passwd"));
            var d2 = new SKDocument(new NSUrl("file:///etc/fstab"));

            idx.AddDocument(d1, "text/plain", true);

            idx.AddDocumentWithText(d2, "This file contains some text like an Apple and an Orange", true);

            const int max = 10;

            nint [] ids    = new nint [max];
            float[] scores = new float[max];
            nint    nfound;
            bool    more;

            using (var search = idx.Search("some", SKSearchOptions.SpaceMeansOr)) {
                more = search.FindMatches(max, ref ids, ref scores, 1, out nfound);
                Assert.IsFalse(more);

                for (nint i = 0; i < nfound; i++)
                {
                    var doc = idx.GetDocument(ids [i]);
                    Assert.IsNotNull(doc, "TestCreate - GetDocument returned null");
                }
            }

            using (var search = idx.Search("some", SKSearchOptions.SpaceMeansOr)) {
                more = search.FindMatches(max, ref ids, 1, out nfound);
                for (nint i = 0; i < nfound; i++)
                {
                    var doc = idx.GetDocument(ids [i]);
                    Console.WriteLine("Got {0}", doc);
                }
            }

            idx.Compact();
            idx.Flush();
            idx.Close();

            // Now open
            idx = SKIndex.FromUrl(new NSUrl("file://" + path), "myIndex", true);
            Assert.NotNull(idx);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates a PDF document displaying the given identity as QR code and text and
        /// providing some guidance for the user.
        /// </summary>
        /// <param name="fileName">The full file name (including the path) for the document.</param>
        /// <param name="identity">The identity for which to create the document.</param>
        /// <param name="blockTypes">Spciefies a list of block types to include.</param>
        public static void CreateIdentityDocument(string fileName, SQRLIdentity identity, List <ushort> blockTypes)
        {
            if (string.IsNullOrEmpty(fileName) || identity == null)
            {
                throw new ArgumentException(string.Format("{0} and {1} must be specified and valid!",
                                                          nameof(fileName), nameof(identity)));
            }

            float  yPos                   = MARGIN_TOP;
            string title                  = "\"" + identity.IdentityName + "\" " + _loc.GetLocalizationValue("FileDialogFilterName");
            string qrCodeMessage          = _loc.GetLocalizationValue("IdentityDocumentQRCodeMessage");
            string textualIdentityMessage = _loc.GetLocalizationValue("IdentityDocumentTextualIdentityMessage");
            string guidanceMessage        = _loc.GetLocalizationValue("IdentityDocumentGuidanceMessage");
            var    identityBytes          = identity.ToByteArray(includeHeader: true, blockTypes);
            string textualIdentity        = SQRL.GenerateTextualIdentityBase56(identityBytes);

            var metadata = new SKDocumentPdfMetadata
            {
                Author          = _assemblyName,
                Creation        = DateTime.Now,
                Creator         = _assemblyName,
                Keywords        = "SQRL,Identity",
                Modified        = DateTime.Now,
                Producer        = "SkiaSharp",
                Subject         = "SQRL Identity Document",
                Title           = "SQRL Identity Document",
                EncodingQuality = 300,
                RasterDpi       = 300
            };

            using (SKBitmap qrCode = CreateQRCode(identityBytes))
                using (var stream = new SKFileWStream(fileName))
                    using (var document = SKDocument.CreatePdf(stream, metadata))
                        using (var canvas = document.BeginPage(PAGE_WIDTH, PAGE_HEIGHT))
                        {
                            float qrCodeWidth  = (qrCode.Width <= QRCODE_MAX_SIZE) ? qrCode.Width : QRCODE_MAX_SIZE;
                            float qrCodeHeight = (qrCode.Height <= QRCODE_MAX_SIZE) ? qrCode.Height : QRCODE_MAX_SIZE;
                            float qrCodeXPos   = PAGE_WIDTH / 2 - qrCodeWidth / 2;

                            yPos += 10 + DrawTextBlock(canvas, title, yPos, _fontBold, 23, SKColors.Black);
                            yPos += -15 + DrawTextBlock(canvas, qrCodeMessage, yPos, _fontRegular, 12, SKColors.DarkGray, SKTextAlign.Left, 1.3f);
                            canvas.DrawBitmap(qrCode, new SKRect(qrCodeXPos, yPos, qrCodeXPos + qrCodeWidth, yPos + qrCodeHeight));
                            yPos += qrCodeHeight + 15;
                            yPos += 10 + DrawTextBlock(canvas, textualIdentityMessage, yPos, _fontRegular, 12, SKColors.DarkGray, SKTextAlign.Left, 1.3f);
                            yPos += 15 + DrawTextBlock(canvas, textualIdentity, yPos, _fontMonoBold, 12, SKColors.Black, SKTextAlign.Center, 1.3f);
                            yPos += 00 + DrawTextBlock(canvas, guidanceMessage, yPos, _fontRegular, 12, SKColors.DarkGray, SKTextAlign.Left, 1.3f);
                            DrawFooter(canvas);

                            document.EndPage();
                            document.Close();
                        }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates a PDF document prominently displaying the given <paramref name="rescueCode"/>
        /// and <paramref name="identityName"/>, providing additional guidance for the user.
        /// </summary>
        /// <param name="fileName">The full file name (including the path) for the document to be created.</param>
        /// <param name="rescueCode">The rescue code to be printed to the document.</param>
        /// <param name="identityName">The name of the identity. This is optional, just
        /// pass <c>null</c> if no identity name should be printed to the pdf file.</param>
        public static void CreateRescueCodeDocument(string fileName, string rescueCode, string identityName = null)
        {
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(rescueCode))
            {
                throw new ArgumentException(string.Format("{0} and {1} must be specified!",
                                                          nameof(fileName), nameof(rescueCode)));
            }

            identityName = identityName != null ? identityName : "";

            _pageNr = 0;
            string title           = _loc.GetLocalizationValue("RescueCodeDocumentTitle");
            string warning         = _loc.GetLocalizationValue("RescueCodeDocumentDiscardWarning");
            string text            = _loc.GetLocalizationValue("RescueCodeDocumentText");
            string identityLabel   = _loc.GetLocalizationValue("IdentityNameLabel");
            string rescueCodeLabel = _loc.GetLocalizationValue("RescueCodeLabel");

            var metadata = new SKDocumentPdfMetadata
            {
                Author   = _assemblyName,
                Creation = DateTime.Now,
                Creator  = _assemblyName,
                Keywords = "SQRL,Rescue code",
                Modified = DateTime.Now,
                Producer = "SkiaSharp",
                Subject  = "SQRL Rescue Code Document",
                Title    = "SQRL Rescue Code Document"
            };

            using (var stream = new SKFileWStream(fileName))
                using (_document = SKDocument.CreatePdf(stream, metadata))
                {
                    StartNextPage();
                    DrawHeader();

                    _yPos = MARGIN_TOP + HEADER_ICON_SIZE + 80;
                    DrawTextBlock(title, _fontBold, 25, SKColors.Black, 15f);
                    DrawTextBlock(warning, _fontBold, 20, SKColors.Red, 20f);
                    DrawTextBlock(text, _fontRegular, 12, SKColors.DarkGray, 30f, SKTextAlign.Left, 1.3f);

                    if (!string.IsNullOrEmpty(identityName))
                    {
                        DrawTextBlock(identityLabel, _fontRegular, 12, SKColors.DarkGray, 15f);
                        DrawTextBlock(identityName, _fontBold, 16, SKColors.Black);
                    }
                    DrawTextBlock(rescueCodeLabel, _fontRegular, 12, SKColors.DarkGray, 25f);
                    DrawTextBlock(rescueCode, _fontBold, 24, SKColors.Black);

                    EndPage();
                    _document.Close();
                }
        }
Ejemplo n.º 24
0
 /// <inheritdoc/>
 public void Save(Stream stream, IProjectContainer project)
 {
     using var pdf = SKDocument.CreatePdf(stream, _targetDpi);
     foreach (var document in project.Documents)
     {
         foreach (var container in document.Pages)
         {
             Add(pdf, container);
         }
     }
     pdf.Close();
     _renderer.ClearCache();
 }
Ejemplo n.º 25
0
 public static void ToFile(string fileName, IEnumerable <IVisual> visuals)
 {
     using var doc = SKDocument.CreatePdf(fileName);
     foreach (var visual in visuals)
     {
         var bounds       = visual.Bounds;
         var page         = doc.BeginPage((float)bounds.Width, (float)bounds.Height);
         var renderTarget = SkiaRenderTarget.Create(page);
         ImmediateRenderer.Render(visual, renderTarget);
         doc.EndPage();
     }
     doc.Close();
 }
Ejemplo n.º 26
0
 public static void ToFile(string fileName, IEnumerable <IVisual> visuals)
 {
     using var doc = SKDocument.CreatePdf(fileName);
     foreach (var visual in visuals)
     {
         var bounds = visual.Bounds;
         var page   = doc.BeginPage((float)bounds.Width, (float)bounds.Height);
         using var context = new DrawingContext(DrawingContextHelper.WrapSkiaCanvas(page, SkiaPlatform.DefaultDpi));
         ImmediateRenderer.Render(visual, context);
         doc.EndPage();
     }
     doc.Close();
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates a PDF document prominently displaying the given rescue code and
        /// providing some guidance for the user.
        /// </summary>
        /// <param name="fileName">The full file name (including the path) for the document.</param>
        /// <param name="rescueCode">The rescue code to be printed to the document.</param>
        /// <param name="identityName">The name of the identity. This is optional, just
        /// pass <c>null</c> if no identity name should be printed to the pdf file.</param>
        public static void CreateRescueCodeDocument(string fileName, string rescueCode, string identityName = null)
        {
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(rescueCode))
            {
                throw new ArgumentException(string.Format("{0} and {1} must be specified!",
                                                          nameof(fileName), nameof(rescueCode)));
            }

            identityName = identityName != null ? identityName : "";

            float  yPos            = MARGIN_TOP + HEADER_ICON_SIZE + 80;
            string title           = _loc.GetLocalizationValue("RescueCodeDocumentTitle");
            string warning         = _loc.GetLocalizationValue("RescueCodeDocumentDiscardWarning");
            string text            = _loc.GetLocalizationValue("RescueCodeDocumentText");
            string identityLabel   = _loc.GetLocalizationValue("IdentityNameLabel");
            string rescueCodeLabel = _loc.GetLocalizationValue("RescueCodeLabel");

            var metadata = new SKDocumentPdfMetadata
            {
                Author   = _assemblyName,
                Creation = DateTime.Now,
                Creator  = _assemblyName,
                Keywords = "SQRL,Rescue code",
                Modified = DateTime.Now,
                Producer = "SkiaSharp",
                Subject  = "SQRL Rescue Code Document",
                Title    = "SQRL Rescue Code Document"
            };

            using (var stream = new SKFileWStream(fileName))
                using (var document = SKDocument.CreatePdf(stream, metadata))
                    using (var canvas = document.BeginPage(PAGE_WIDTH, PAGE_HEIGHT))
                    {
                        DrawHeader(canvas);
                        yPos += 10 + DrawTextBlock(canvas, title, yPos, _fontBold, 25, SKColors.Black);
                        yPos += 20 + DrawTextBlock(canvas, warning, yPos, _fontBold, 20, SKColors.Red);
                        yPos += 30 + DrawTextBlock(canvas, text, yPos, _fontRegular, 12, SKColors.DarkGray, SKTextAlign.Left, 1.3f);
                        if (!string.IsNullOrEmpty(identityName))
                        {
                            yPos += 05 + DrawTextBlock(canvas, identityLabel, yPos, _fontRegular, 12, SKColors.DarkGray);
                            yPos += 15 + DrawTextBlock(canvas, identityName, yPos, _fontBold, 16, SKColors.Black);
                        }
                        yPos += 10 + DrawTextBlock(canvas, rescueCodeLabel, yPos, _fontRegular, 12, SKColors.DarkGray);
                        yPos += 15 + DrawTextBlock(canvas, rescueCode, yPos, _fontBold, 24, SKColors.Black);
                        DrawFooter(canvas);

                        document.EndPage();
                        document.Close();
                    }
        }
Ejemplo n.º 28
0
        protected override void OnTapped()
        {
            base.OnTapped();

            var path = Path.Combine(root, $"{Guid.NewGuid().ToString("N")}.xps");

            using (var stream = new SKFileWStream(path))
                using (var document = SKDocument.CreateXps(stream))
                    using (var paint = new SKPaint())
                    {
                        if (document == null)
                        {
                            xpsSupported = false;
                            Refresh();
                            return;
                        }

                        paint.TextSize    = 64.0f;
                        paint.IsAntialias = true;
                        paint.Color       = (SKColor)0xFF9CAFB7;
                        paint.IsStroke    = true;
                        paint.StrokeWidth = 3;
                        paint.TextAlign   = SKTextAlign.Center;

                        var width  = 840;
                        var height = 1188;

                        // draw page 1
                        using (var xpsCanvas = document.BeginPage(width, height))
                        {
                            // draw contents
                            xpsCanvas.DrawText("...XPS 1/2...", width / 2, height / 4, paint);
                            document.EndPage();
                        }

                        // draw page 2
                        using (var xpsCanvas = document.BeginPage(width, height))
                        {
                            // draw contents
                            xpsCanvas.DrawText("...XPS 2/2...", width / 2, height / 4, paint);
                            document.EndPage();
                        }

                        // end the doc
                        document.Close();
                    }

            // display to the user
            SamplesManager.OnOpenFile(path);
        }
Ejemplo n.º 29
0
        public void PdfFileWithNonASCIIPathIsClosed()
        {
            var path = Path.Combine(PathToImages, Guid.NewGuid().ToString("D") + "上田雅美.pdf");

            using (var doc = SKDocument.CreatePdf(path))
            {
                Assert.NotNull(doc);
                Assert.NotNull(doc.BeginPage(100, 100));

                doc.EndPage();
                doc.Close();
            }

            File.Delete(path);
        }
Ejemplo n.º 30
0
        internal static void GeneratePdf(Stream stream, IDocument document)
        {
            var content  = ElementExtensions.Create(document.Compose);
            var metadata = document.GetMetadata();

            using var pdf = SKDocument.CreatePdf(stream, MapMetadata(metadata));
            var totalPages = 1;

            while (true)
            {
                var spacePlan = content.Measure(metadata.Size);

                using var skiaCanvas = pdf.BeginPage(metadata.Size.Width, metadata.Size.Height);
                var canvas = new Canvas(skiaCanvas);

                try
                {
                    content.Draw(canvas, metadata.Size);
                }
                catch (Exception exception)
                {
                    pdf.Close();
                    stream.Close();

                    throw new DocumentDrawingException("An exception occured during document drawing.", exception);
                }

                pdf.EndPage();

                if (totalPages >= metadata.DocumentLayoutExceptionThreshold)
                {
                    pdf.Close();
                    stream.Close();

                    throw new DocumentLayoutException("Composed layout generates infinite document.");
                }

                if (spacePlan is FullRender)
                {
                    break;
                }

                totalPages++;
            }

            pdf.Close();
            stream.Dispose();
        }