Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

c# - Crop Pdf Page While Converting it to Image

I'm trying to crop the PDF/Image File Before I convert it to Image. So in this code i generate a pdf file, and I want to crop it Before / After I convert it to image.

The issue here is how I can set or crop the image i generate from the pdf?

Here is the Code I'm using:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using IronPdf;
using System.Windows.Media.Imaging;
using Syncfusion.Windows.PdfViewer;
using Syncfusion.Pdf.Parsing;
using System.Windows;
using System.IO;
namespace WpfApp2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();         
        }

        private async void GeneratePdf()
        {
            var Renderer = new IronPdf.HtmlToPdf();

            Renderer.PrintOptions.SetCustomPaperSizeInInches(12.5, 20);
            Renderer.PrintOptions.PaperOrientation= PdfPrintOptions.PdfPaperOrientation.Portrait;
            Renderer.PrintOptions.EnableJavaScript = true;
            Renderer.PrintOptions.RenderDelay = 50; //ms
            Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
            Renderer.PrintOptions.DPI = 300;
            Renderer.PrintOptions.FitToPaperWidth = true;
            Renderer.PrintOptions.JpegQuality = 100;
            Renderer.PrintOptions.GrayScale = false;
            Renderer.PrintOptions.FitToPaperWidth = true;
            Renderer.PrintOptions.InputEncoding = Encoding.UTF8;
            Renderer.PrintOptions.Zoom = 100;
            Renderer.PrintOptions.CreatePdfFormsFromHtml = true;
            Renderer.PrintOptions.MarginTop = 60;  //millimeters
            Renderer.PrintOptions.MarginLeft = 20;  //millimeters
            Renderer.PrintOptions.MarginRight = 30;  //millimeters
            Renderer.PrintOptions.MarginBottom = 20;  //millimeters
            Renderer.PrintOptions.FirstPageNumber = 1; //use 2 if a coverpage  will be 
            Renderer.PrintOptions.InputEncoding = System.Text.Encoding.UTF8;

            var time = DateTime.Now;
            Renderer.PrintOptions.Header = new HtmlHeaderFooter()
            {
                HtmlFragment = "<img src='https://i.imgur.com/QtFjt8p.jpg'>",
                DrawDividerLine=true,

            };
            var pdf = Renderer.RenderHtmlAsPdf("" +
                "<p style='text-align: center;font-size: 25px;font-family: Calibri, sans-serif';text-decoration: underline;>" + textbox3.Text+"</p>"
                );

            var BackgroundStamp = new HtmlStamp() { Html = "<img src='https://i.imgur.com/U8MUT3q.png'/>", Width = 100, Height = 100, Opacity = 90, Left = 100, Top = 200, ZIndex = HtmlStamp.StampLayer.BehindExistingPDFContent };
            pdf.StampHTML(BackgroundStamp);

            pdf.SaveAs("Watermarked.pdf");
            pdf.Dispose();
            Thread.Sleep(6000);


            PdfViewerControl pdfViewer = new PdfViewerControl();
            //Load the input PDF file
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument("Watermarked.pdf");
            pdfViewer.Load(loadedDocument);
            
            //Export the particular PDF page as image at the page index of 0.
            BitmapSource image = pdfViewer.ExportAsImage(0);
            //Setup the output path
            if (image != null)
            {
                //Initialize the new PngBitmapEncoder
                BitmapEncoder encoder = new PngBitmapEncoder();
                //Create the bitmap frame using the bitmap source and add it to the encoder.
                encoder.Frames.Add(BitmapFrame.Create(image));
                //Create the file stream for the output in the desired image format.
                FileStream stream = new FileStream("Watermarked.png", FileMode.Create);
                //Save the stream, so that the image will be generated in the output location.
                encoder.Save(stream);
            }
            //Dispose the document.
            loadedDocument.Dispose();
            loadedDocument = null;






            //  await Task.Run(() => croppdf());
        }
       
        public async void croppdf()
        {
          

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            GeneratePdf();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
    }
}

If someone can help me with this, I tried ,any solutions but did not worked for me actually.

question from:https://stackoverflow.com/questions/65926488/crop-pdf-page-while-converting-it-to-image

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would use CroppedBitmap

...
//Export the particular PDF page as image at the page index of 0.
BitmapSource image = pdfViewer.ExportAsImage(0);
//Setup the output path
if (image != null)
{
    // init croppedBitmap
    CroppedBitmap croppedBitmap = new CroppedBitmap(image,new Int32Rect(5, 5, (int)(image.Width-10), (int)(image.Height-10)));
    //Initialize the new PngBitmapEncoder
    BitmapEncoder encoder = new PngBitmapEncoder();
    //Create the bitmap frame using the cropped bitmap source and add it to the encoder.
    encoder.Frames.Add(BitmapFrame.Create(croppedBitmap));
    //Create the file stream for the output in the desired image format.
    FileStream stream = new FileStream("Watermarked.png", FileMode.Create);
    //Save the stream, so that the image will be generated in the output location.
    encoder.Save(stream);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...