Пример #1
0
        public string GetPdf()
        {
            IEnumerable <string> imageUrls = this.GetImageUrls().ToList();
            string fileName = $"{Guid.NewGuid().ToString()}.pdf";

            using (var document = new PdfDocument())
            {
                foreach (var imageUrl in imageUrls)
                {
                    PdfPage   page = document.AddPage();
                    WebClient wc   = new WebClient();
                    using (MemoryStream stream = new MemoryStream(wc.DownloadData(imageUrl)))
                    {
                        using (XImage img = XImage.FromStream(stream))
                        {
                            page.Width  = img.Width;
                            page.Height = img.Height;
                            XGraphics gfx = XGraphics.FromPdfPage(page);
                            gfx.DrawImage(img, 0, 0, img.Width, img.Height);
                        }
                    }
                }
                document.Save(fileName);
                return(fileName);
            }
        }
Пример #2
0
        public static Stream CreatePDFFromImages(this byte[][] images)
        {
            const double margin = 50d;

            PdfDocument document = new PdfDocument();

            foreach (var imageBytes in images)
            {
                PdfPage page = document.AddPage();

                XGraphics gfx = XGraphics.FromPdfPage(page);

                Stream imageStream = new MemoryStream(imageBytes);
                XImage image       = XImage.FromStream(imageStream);
                gfx.DrawImage(image, margin, margin, page.Width - margin, page.Height - margin);
            }

            var pdfStream = new MemoryStream();

            document.Save(pdfStream);

            // For debugging ---
            //using (var fileStream = File.Create("C:\\temp\\outputpdf.pdf"))
            //{
            //    pdfStream.Seek(0, SeekOrigin.Begin);
            //    pdfStream.CopyTo(fileStream);
            //}
            pdfStream.Seek(0, SeekOrigin.Begin);

            return(pdfStream);
        }
Пример #3
0
        static public void XpsToBmp(string xpsFile, string source, PageSize pageSize)
        {
            var xps      = new XpsDocument(xpsFile, FileAccess.Read);
            var sequence = xps.GetFixedDocumentSequence();

            using (var doc = new PdfDocument())
            {
                for (var pageCount = 0; pageCount < sequence.DocumentPaginator.PageCount; ++pageCount)
                {
                    DocumentPage page     = sequence.DocumentPaginator.GetPage(pageCount);
                    var          toBitmap = new RenderTargetBitmap((int)page.Size.Width, (int)page.Size.Height, 96, 96, PixelFormats.Default);
                    toBitmap.Render(page.Visual);

                    var bmpEncoder = new BmpBitmapEncoder();
                    bmpEncoder.Frames.Add(BitmapFrame.Create(toBitmap));

                    using (var ms = new MemoryStream())
                    {
                        bmpEncoder.Save(ms);

                        doc.Pages.Add(new PdfPage {
                            Size = pageSize, Orientation = GetOrientation((int)page.Size.Width)
                        });

                        var xgr = XGraphics.FromPdfPage(doc.Pages[pageCount]);
                        var img = XImage.FromStream(ms);

                        xgr.DrawImage(img, 0, 0);
                    }
                }

                doc.Save(source);
            }
        }
Пример #4
0
        public Stream Join(IEnumerable <Document> documents)
        {
            var documentStream = new MemoryStream();
            var outputDocument = new PdfDocument();

            foreach (var document in documents)
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }

                var page    = new PdfPage(outputDocument);
                var context = XGraphics.FromPdfPage(page);
                using (var file = fileReader.AttemptToReadFile(document.FullPath))
                    using (var image = XImage.FromStream(file))
                    {
                        context.DrawImage(image, new XPoint(0D, 0D));
                        outputDocument.AddPage(page);
                    }
            }

            if (outputDocument.PageCount > 0)
            {
                outputDocument.Save(documentStream, closeStream: false);
            }

            documentStream.Seek(0L, SeekOrigin.Begin);
            return(documentStream);
        }
Пример #5
0
        XImage CreateXImage(string uri)
        {
            if (uri.StartsWith("base64:"))
            {
                string base64 = uri.Substring("base64:".Length);
                byte[] bytes  = Convert.FromBase64String(base64);
#if WPF || CORE_WITH_GDI || GDI
                // WPF stores a reference to the stream internally. We must not destroy the stream here, otherwise rendering the PDF will fail.
                // Same for GDI. CORE currently uses the GDI implementation.
                // We have to rely on the garbage collector to properly dispose the MemoryStream.
                {
                    Stream stream = new MemoryStream(bytes);
                    XImage image  = XImage.FromStream(stream);
                    return(image);
                }
#else
                using (Stream stream = new MemoryStream(bytes))
                {
                    XImage image = XImage.FromStream(stream);
                    return(image);
                }
#endif
            }
            return(XImage.FromFile(uri));
        }
        public PdfDocumentInfo BuildDocument(string directoryPath, PdfClientPdfDocument document)
        {
            EnsureArg.IsNotNullOrEmpty(directoryPath, nameof(directoryPath));
            EnsureArg.IsNotNull(document, nameof(document));

            using var pdfDocument = new PdfDocument();

            foreach (var documentPage in document.Pages)
            {
                var page = pdfDocument.AddPage();
                page.Size = PdfSharpCore.PageSize.A4;

                using var gfx       = XGraphics.FromPdfPage(page);
                using XImage xImage = XImage.FromStream(() => documentPage.DataStream);

                gfx.DrawImage(xImage, 0, 0, page.Width.Point, page.Height.Point);
            }

            pdfDocument.Save($"{directoryPath}/{document.Title}.pdf");

            return(new PdfDocumentInfo
            {
                Created = DateTime.UtcNow,
                FilePath = $"{directoryPath}/{document.Title}.pdf",
            });
        }
Пример #7
0
        /// <summary>
        /// On image load in renderer set the image by event async.
        /// </summary>
        public static void ImageLoad(HtmlImageLoadEventArgs e, bool pdfSharp)
        {
            var    img  = TryLoadResourceImage(e.Src);
            XImage xImg = null;

            if (img != null)
            {
                using (var ms = new MemoryStream())
                {
                    img.Save(ms, img.RawFormat);
                    xImg = img != null?XImage.FromStream(ms) : null;
                }
            }

            object imgObj;

            if (pdfSharp)
            {
                imgObj = xImg;
            }
            else
            {
                imgObj = img;
            }

            if (!e.Handled && e.Attributes != null)
            {
                if (e.Attributes.ContainsKey("byevent"))
                {
                    int delay;
                    if (Int32.TryParse(e.Attributes["byevent"], out delay))
                    {
                        e.Handled = true;
                        ThreadPool.QueueUserWorkItem(state =>
                        {
                            Thread.Sleep(delay);
                            e.Callback("https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-snc7/c0.44.403.403/p403x403/318890_10151195988833836_1081776452_n.jpg");
                        });
                        return;
                    }
                    else
                    {
                        e.Callback("http://sphotos-a.xx.fbcdn.net/hphotos-ash4/c22.0.403.403/p403x403/263440_10152243591765596_773620816_n.jpg");
                        return;
                    }
                }
                else if (e.Attributes.ContainsKey("byrect"))
                {
                    var split = e.Attributes["byrect"].Split(',');
                    var rect  = new Rectangle(Int32.Parse(split[0]), Int32.Parse(split[1]), Int32.Parse(split[2]), Int32.Parse(split[3]));
                    e.Callback(imgObj ?? TryLoadResourceImage("htmlicon"), rect.X, rect.Y, rect.Width, rect.Height);
                    return;
                }
            }

            if (img != null)
            {
                e.Callback(imgObj);
            }
        }
Пример #8
0
        /// <summary>
        ///     Converts Image(s) to PDF document
        /// </summary>
        /// <param name="formFiles"></param>
        /// <returns>PDF document stream</returns>
        public async Task <MemoryStream> ConvertImagesToPDF(IFormFileCollection formFiles)
        {
            _logger.LogInformation("ConverImagesToPdf started");
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            PdfDocument pdfDocument = new PdfDocument();

            foreach (var file in formFiles)
            {
                if (!IsFileAnImage(file))
                {
                    _logger.LogInformation("File was not an Image");
                    return(null);
                }

                MemoryStream memoryStream = new MemoryStream();
                await file.CopyToAsync(memoryStream);

                PdfPage   page      = pdfDocument.Pages.Add();
                XGraphics xGraphics = XGraphics.FromPdfPage(page);
                XImage    xImage    = XImage.FromStream(memoryStream);
                xGraphics.DrawImage(xImage, 0, 0, 612, 792);
            }

            MemoryStream resultMemoryStream = new MemoryStream();

            pdfDocument.Save(resultMemoryStream);
            return(resultMemoryStream);
        }
Пример #9
0
        private void CreatePDF(Dictionary <string, List <byte> > images)
        {
            var resultDirectory = Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "Result", DateTime.Today.ToString("dd-MM-yy")));
            var pdfName         = Path.Combine(resultDirectory.FullName, $"{Guid.NewGuid().ToString()}.pdf");

            int i = 0;

            try
            {
                PdfDocument document = new PdfDocument();

                foreach (var fileArray in images.Values.Select(value => value.ToArray()))
                {
                    var page = document.AddPage();
                    using (var stream = new MemoryStream(fileArray))
                    {
                        XGraphics gfx = XGraphics.FromPdfPage(page);

                        gfx.DrawImage(XImage.FromStream(stream), new XRect(0, 0, page.Width, page.Height));
                    }
                }

                document.Save(pdfName);
                document.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            System.Drawing.Bitmap bmpScreenshot = new System.Drawing.Bitmap((int)CanvasPrint.ActualWidth, (int)CanvasPrint.ActualHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var gfxScreenshot = Graphics.FromImage(bmpScreenshot);

            System.Drawing.Point p = System.Drawing.Point.Empty;
            gfxScreenshot.CopyFromScreen(new System.Drawing.Point((int)Left, (int)Top), p, new System.Drawing.Size(width: 800, height: 800));//Screen size

            PdfDocument doc = new PdfDocument();

            doc.Pages.Add(new PdfPage());
            Stream memoryStream = new MemoryStream();

            bmpScreenshot.Save(memoryStream, ImageFormat.Bmp);
            XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
            XImage    img = XImage.FromStream(memoryStream);

            xgr.DrawImage(img, -6, -24);

            string user_Url_Desctop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            doc.Save($"{user_Url_Desctop}\\STATUS {textBoxNameFile.Text}.pdf");//Url to save Name pdf file
            doc.Close();
            MessageBox.Show($"File STATUS {textBoxNameFile.Text}.pdf Save to your Desctop");
            System.Diagnostics.Process.Start($"{user_Url_Desctop}\\STATUS {textBoxNameFile.Text}.pdf");//Url open file pdf
        }
Пример #11
0
        public Stream ImageToPdf(Stream imageStream, int pageWidth)
        {
            Stream stream = default;

            using (var document = new PdfDocument())
            {
                var page = document.AddPage();

                using (XImage img = XImage.FromStream(() => { return(imageStream); }))
                {
                    var height = img.PixelHeight;

                    // Change PDF Page size to match image
                    page.Width  = pageWidth;
                    page.Height = height;

                    XGraphics gfx = XGraphics.FromPdfPage(page);
                    gfx.DrawImage(img, 0, 0, pageWidth, height);
                }
                stream = new MemoryStream();

                document.Save(stream);

                stream.Position = 0;
            }

            return(stream);
        }
Пример #12
0
        private void DrawForAndroid(XGraphics page, SearchBar searchBar, XRect bounds, double scaleFactor)
        {
            Color bgColor   = searchBar.BackgroundColor != default(Color) ? searchBar.BackgroundColor : Color.Black;
            Color textColor = searchBar.TextColor != default(Color) ? searchBar.TextColor : Color.Gray;
            XFont font      = new XFont(searchBar.FontFamily ?? GlobalFontSettings.FontResolver.DefaultFontName, searchBar.FontSize * scaleFactor);

            XImage searchIcon = XImage.FromStream(() => {
                var assembly = typeof(PdfSearchBarRenderer).GetTypeInfo().Assembly;
                return(assembly.GetManifestResourceStream($"Plugin.Xamarin.Forms.PdfSharp.Shared.Icons.search.png"));
            });
            double iconSize = bounds.Height * 0.8;

            page.DrawRectangle(bgColor.ToXBrush(), bounds);
            page.DrawLine(new XPen(Color.LightBlue.ToXColor(), 1 * scaleFactor),
                          new XPoint(bounds.X + iconSize + 6 * scaleFactor, bounds.Y + bounds.Height - 2 * scaleFactor),
                          new XPoint(bounds.X + bounds.Width - 2 * scaleFactor, bounds.Y + bounds.Height - 2 * scaleFactor));

            page.DrawImage(searchIcon, new XRect(bounds.X + 5 * scaleFactor, bounds.Y + bounds.Height * 0.1, iconSize, iconSize), new System.Threading.CancellationToken());

            if (!string.IsNullOrEmpty(searchBar.Text))
            {
                page.DrawString(searchBar.Text, font, textColor.ToXBrush(), new XRect(bounds.X + iconSize + 12 * scaleFactor, bounds.Y, bounds.Width - iconSize, bounds.Height), new XStringFormat {
                    Alignment     = XStringAlignment.Near,
                    LineAlignment = XLineAlignment.Center
                });
            }
        }
Пример #13
0
        public static void GeneratePDF(IEnumerable <Image> images, string outPath)
        {
            if (images == null) // || !images.Any())
            {
                throw new ArgumentException("No images to put in PDF file");
            }
            if (!Directory.Exists(Path.GetDirectoryName(outPath)))
            {
                throw new ArgumentException("Output folder does not exist");
            }

            PdfDocument pdfDoc = new PdfDocument(outPath);

            // Title page

            foreach (Image img in images)
            {
                PdfPage page = pdfDoc.AddPage();
                page.Size        = PageSize.A4;
                page.Orientation = PageOrientation.Landscape;
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, ImageFormat.Png);
                    using (XGraphics gfx = XGraphics.FromPdfPage(page))
                    {
                        ms.Seek(0, SeekOrigin.Begin);
                        XImage image    = XImage.FromStream(ms);
                        double ptWidth  = image.PixelWidth * 72 / 300.0;
                        double ptHeight = image.PixelHeight * 72 / 300.0;
                        gfx.DrawImage(image, 36, 24, ptWidth, ptHeight);
                    }
                }
            }
            pdfDoc.Close();
        }
Пример #14
0
        private bool BuildDocumentWithoutOcr(ProgressHandler progressCallback, CancellationToken cancelToken, PdfDocument document, PdfCompat compat, ICollection <ScannedImage.Snapshot> snapshots)
        {
            int progress = 0;

            progressCallback(progress, snapshots.Count);
            foreach (var snapshot in snapshots)
            {
                bool importedPdfPassThrough = snapshot.Source.FileFormat == null && !snapshot.TransformList.Any();

                if (importedPdfPassThrough)
                {
                    CopyPdfPageToDoc(document, snapshot.Source);
                }
                else
                {
                    using (Stream stream = scannedImageRenderer.RenderToStream(snapshot).Result)
                        using (var img = XImage.FromStream(stream))
                        {
                            if (cancelToken.IsCancellationRequested)
                            {
                                return(false);
                            }

                            PdfPage page = document.AddPage();
                            DrawImageOnPage(page, img, compat);
                        }
                }
                progress++;
                progressCallback(progress, snapshots.Count);
            }
            return(true);
        }
Пример #15
0
        private PointF drawImage(Stream symbolStream, PdfDocument document, ref PdfPage page, ref XGraphics gfx, PointF offset, String overlay)
        {
            XImage image = XImage.FromStream(symbolStream);
            XSize size = image.Size;
            var ImageScale = ImageSize / size.Height;
            size.Width *= ImageScale;
            size.Height *= ImageScale;

            if (page == null)
                offset = createPage(document, ref page, ref gfx);
            else if (offset.X + size.Width > page.Width - BorderWidthRight)
            {
                // new Row
                offset.X = BorderWidthLeft;
                offset.Y += (Single)size.Height + RowDistance;
            }

            if (offset.Y + size.Height > page.Height - BorderWidthBottom)
                offset = createPage(document, ref page, ref gfx);

            gfx.DrawImage(image, offset.X, offset.Y, size.Width, size.Height);

            // Border
            gfx.DrawRectangle(new XPen(XColor.FromArgb(Color.Gray.ToArgb()), 0.2), offset.X, offset.Y, size.Width, size.Height);

            // Draw the overlay
            drawOverlay(overlay, (int)(size.Width + ColumnDistance - 2), document, ref page, ref gfx, new PointF(offset.X, (Single)(offset.Y + size.Height)));

            offset.X += (Single)size.Width + ColumnDistance;

            return offset;
        }
Пример #16
0
        public static void SaveImageAsPdf(Stream imageStream, string fileName)
        {
            try
            {
                using (var document = new PdfDocument())
                {
                    PdfPage page = document.AddPage();
                    using (XImage image = XImage.FromStream(imageStream))
                    {
                        double imageWidth  = image.PointWidth;
                        double imageHeight = image.PointHeight;
                        double pageWidth   = page.Width;
                        double pageHeight  = page.Height;

                        XGraphics gfx = XGraphics.FromPdfPage(page);
                        gfx.DrawImage(image, (pageWidth - imageWidth) / 2, (pageHeight - imageHeight) / 2);
                    }

                    var physicalPath = HttpContext.Current.Server.MapPath(fileName);
                    document.Save(physicalPath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #17
0
        public XImage ImgToXimg(Bitmap img)
        {
            MemoryStream strm = new MemoryStream();

            img.Save(strm, ImageFormat.Png);
            return(XImage.FromStream(strm));
        }
Пример #18
0
        private void DrawForUWP(XGraphics page, SearchBar searchBar, XRect bounds, double scaleFactor)
        {
            Color  bgColor    = searchBar.BackgroundColor != default(Color) ? searchBar.BackgroundColor : Color.White;
            XFont  font       = new XFont(searchBar.FontFamily ?? GlobalFontSettings.FontResolver.DefaultFontName, searchBar.FontSize * scaleFactor);
            XImage searchIcon = XImage.FromStream(() => {
                var assembly = typeof(PdfSearchBarRenderer).GetTypeInfo().Assembly;
                return(assembly.GetManifestResourceStream($"PdfSharp.Xamarin.Forms.Icons.search.png"));
            });

            page.DrawRectangle(bgColor.ToXBrush(), bounds);
            page.DrawRectangle(new XPen(Color.Gray.ToXColor(), 2 * scaleFactor), bounds);

            if (!string.IsNullOrEmpty(searchBar.Text))
            {
                Color textColor = searchBar.TextColor != default(Color) ? searchBar.TextColor : Color.Black;
                page.DrawString(searchBar.Text, font, textColor.ToXBrush(), new XRect(5 * scaleFactor + bounds.X, bounds.Y, bounds.Width, bounds.Height), new XStringFormat {
                    Alignment     = XStringAlignment.Near,
                    LineAlignment = XLineAlignment.Center
                });
            }
            else if (!string.IsNullOrEmpty(searchBar.Placeholder))
            {
                Color placeholderColor = searchBar.PlaceholderColor != default(Color) ? searchBar.PlaceholderColor : Color.Gray;
                page.DrawString(searchBar.Placeholder, font, placeholderColor.ToXBrush(), new XRect(5 * scaleFactor + bounds.X, bounds.Y, bounds.Width, bounds.Height), new XStringFormat {
                    Alignment     = XStringAlignment.Near,
                    LineAlignment = XLineAlignment.Center
                });
            }

            double imgSize = bounds.Height - 4 * scaleFactor;

            page.DrawImage(searchIcon, new XRect(bounds.X + bounds.Width - imgSize - 2 * scaleFactor, bounds.Y + 2 * scaleFactor, imgSize, imgSize), new System.Threading.CancellationToken());
        }
Пример #19
0
        private bool BuildDocumentWithoutOcr(Func<int, bool> progressCallback, PdfDocument document, PdfCompat compat, IEnumerable<ScannedImage> images)
        {
            int progress = 0;
            foreach (var image in images)
            {
                bool importedPdfPassThrough = image.FileFormat == null && !image.RecoveryIndexImage.TransformList.Any();

                if (importedPdfPassThrough)
                {
                    CopyPdfPageToDoc(document, image);
                }
                else
                {
                    using (Stream stream = scannedImageRenderer.RenderToStream(image))
                    using (var img = XImage.FromStream(stream))
                    {
                        if (!progressCallback(progress))
                        {
                            return false;
                        }

                        PdfPage page = document.AddPage();
                        DrawImageOnPage(page, img, compat);
                    }
                }
                progress++;
            }
            return true;
        }
Пример #20
0
        public override async void CreatePDFLayout(XGraphics page, Image image, XRect bounds, double scaleFactor)
        {
            if (image.BackgroundColor != default(Color))
            {
                page.DrawRectangle(image.BackgroundColor.ToXBrush(), bounds);
            }

            if (image.Source == null)
            {
                return;
            }

            string imageSource = string.Empty;
            XImage img         = null;

            if (image.Source is FileImageSource)
            {
                img = XImage.FromFile((image.Source as FileImageSource).File);
            }
            else if (image.Source is UriImageSource)
            {
                img = XImage.FromFile((image.Source as UriImageSource).Uri.AbsolutePath);
            }
            else if (image.Source is StreamImageSource)
            {
                var stream = await(image.Source as StreamImageSource).Stream.Invoke(new System.Threading.CancellationToken());
                img = XImage.FromStream(() => stream);
            }

            XRect desiredBounds = bounds;

            switch (image.Aspect)
            {
            case Aspect.Fill:
                desiredBounds = bounds;
                break;

            case Aspect.AspectFit:
            {
                double aspectRatio = ((double)img.PixelWidth) / img.PixelHeight;
                if (aspectRatio > (bounds.Width / bounds.Height))
                {
                    desiredBounds.Height = desiredBounds.Width * aspectRatio;
                }
                else
                {
                    desiredBounds.Width = desiredBounds.Height * aspectRatio;
                }
            }
            break;

            //PdfSharp does not support drawing a portion pf image, its not supported
            case Aspect.AspectFill:
                desiredBounds = bounds;
                break;
            }

            page.DrawImage(img, desiredBounds, new System.Threading.CancellationToken());
        }
Пример #21
0
        protected override RImage ImageFromStreamInt(Stream memoryStream)
        {
#if NETCOREAPP2_2
            return(new ImageAdapter(XImage.FromStream(() => memoryStream)));
#else
            return(new ImageAdapter(XImage.FromStream(memoryStream)));
#endif
        }
Пример #22
0
        private static void DrawImage(XGraphics gfx, int x, int y, int width, int height)
        {
            var test = new MemoryStream();

            Properties.Resources.logo_background.Save(test, ImageFormat.Png);
            XImage image = XImage.FromStream(test);

            gfx.DrawImage(image, x, y, width, height);
        }
Пример #23
0
 private static void aaa(XGraphics _param0, Image _param1, int _param2, int _param3)
 {
     using (MemoryStream memoryStream = new MemoryStream())
     {
         _param1.Save((Stream)memoryStream, ImageFormat.Png);
         XImage ximage = XImage.FromStream((Stream)memoryStream);
         _param0.DrawImage(ximage, (double)_param2, (double)_param3, (double)_param1.Width, (double)_param1.Height);
     }
 }
Пример #24
0
 /// <inheritdoc cref="ICanvas"/>
 public float GetImageWidthHeightRatio(Bitmap pngImage)
 {
     using (var stream = new MemoryStream())
     {
         pngImage.Save(stream, ImageFormat.Png);
         var image = XImage.FromStream(stream);
         return((float)(image.PointWidth / image.PointHeight));
     }
 }
Пример #25
0
        /// <inheritdoc cref="ICanvas"/>
        public float GetImageHeight(Bitmap pngImage)
        {
            using (var stream = new MemoryStream())
            {
                pngImage.Save(stream, ImageFormat.Png);
                var image          = XImage.FromStream(stream);
                var absoluteHeight = (float)image.PointHeight;

                return(absoluteHeight / currentDrawingSpace.Height);
            }
        }
Пример #26
0
        public void GenPdf(string[] args)
        {
            string strHostName = System.Net.Dns.GetHostName();
            string pathImgGun  = System.Configuration.ConfigurationSettings.AppSettings["pathImgGun"];
            string pathSavePdf = System.Configuration.ConfigurationSettings.AppSettings["pathSavePdf"];
            // Create a new PDF document
            PdfDocument document = new PdfDocument();

            document.Info.Title = args[1];

            string dirPath = "\\\\" + strHostName + pathImgGun + args[2];

            DirectoryInfo dir = new DirectoryInfo(dirPath);

            string[] fileList = System.IO.Directory.GetFiles(dirPath, "*.jpg", SearchOption.TopDirectoryOnly);

            foreach (var item in fileList)
            {
                PdfPage page = document.AddPage();
                page.Size = PageSize.A4;
                // Get an XGraphics object for drawing
                XGraphics gfx = XGraphics.FromPdfPage(page);

                var ms = new MemoryStream();

                using (var imageA = Image.FromFile(item))
                    using (var newImage = ScaleImage(imageA, 595, 842, 72))
                    {
                        newImage.Save(ms, ImageFormat.Jpeg);
                    }

                XImage image = XImage.FromStream(ms);

                gfx.DrawImage(image, 0, (842 - image.PixelHeight) / 2);

                System.Console.WriteLine("Add image --> " + item);
            }

            string pathEbook = "\\\\" + strHostName + pathSavePdf + args[2];

            pathEbook = pathEbook.Substring(0, pathEbook.Length - 5);
            if (!System.IO.Directory.Exists(pathEbook))
            {
                System.IO.Directory.CreateDirectory(pathEbook);
            }
            // Save the document...
            string filename = "\\\\" + strHostName + pathSavePdf + args[2] + ".pdf";

            System.Console.WriteLine("Save to --> " + filename);
            document.Save(filename);
            // ...and start a viewer.
            //Process.Start(filename);
            System.Console.WriteLine("Success");
        }
Пример #27
0
        private void DrawProfilePicture(User user, XGraphics gfx)
        {
            var imageUrl = user.PersonalData?.ProfilePictureFile?.FileUrl ?? _businessConfiguration.DefaultProfileImagePath;

            using (Stream profilePic = _fileRepository.Get(imageUrl))
            {
                XImage image = XImage.FromStream(() => profilePic);

                gfx.DrawImage(image, 50, 10, 200, 200);
            }
        }
Пример #28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="gfx"></param>
 /// <param name="jpegSamplePath"></param>
 /// <param name="x"></param>
 /// <param name="y"></param>
 private void drawImage(XGraphics gfx, Image img, double x, double y, PdfPage page)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         img.Save(ms, ImageFormat.Jpeg);
         XImage image      = XImage.FromStream(ms);
         double horizontal = (page.Width.Millimeter / 25.4) * 72 - (x * 2);
         double vertical   = (page.Height.Millimeter / 25.4) * 72 - (y * 2);
         gfx.DrawImage(image, x, y, horizontal, vertical);
     }
 }
        public XImage FromURI(string uri)
        {
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(uri);

            webRequest.AllowWriteStreamBuffering = true;
            WebResponse webResponse = webRequest.GetResponse();
            XImage      xImage      = XImage.FromStream(webResponse.GetResponseStream());

            webResponse.Close();
            return(xImage);
        }
Пример #30
0
        private static byte[] GetStream(string[] imageUrl)
        {
            List <Stream> stream = new List <Stream>();

            // byte[] myData = null;
            //try
            //{

            using (var document = new PdfDocument())
            {
                for (var i = 0; i < imageUrl.Length; i++)
                {
                    byte[] bytes = Convert.FromBase64String(imageUrl[i].Replace("data:image/png;base64,", ""));
                    using (var stream2 = new MemoryStream(bytes))
                    {
                        PdfPage page = document.AddPage();


                        using (XImage img = XImage.FromStream(() => stream2))
                        {
                            // Calculate new height to keep image ratio
                            var height = (int)(((double)600 / (double)img.PixelWidth) * img.PixelHeight);

                            // Change PDF Page size to match image
                            page.Width  = 600;
                            page.Height = height;

                            XGraphics gfx = XGraphics.FromPdfPage(page);
                            gfx.DrawImage(img, 0, 0, 600, height);

                            //myData = ReadFully(stream)
                            //  image = System.Drawing.Image.FromStream(stream);
                        }
                    }
                }
                byte[] docBytes;
                using (MemoryStream stream3 = new MemoryStream())
                {
                    // Saves the document as stream
                    document.Save(stream3);
                    document.Close();
                    // Converts the PdfDocument object to byte form.
                    docBytes = stream3.ToArray();
                }

                return(docBytes);
            }
            //  PdfHelper.SaveImageAsPdf(stream, @"E:\ffffi.pdf");
            //   }
            //catch (Exception ex)
            //{
            //    return null;
            //}
        }