Exemple #1
0
        public List <Bitmap> ConvertPagedPdfToBitmaps(System.IO.Stream pdfStream)
        {
            string ghostscriptLibraryPath = "C:\\Program Files (x86)\\gs\\gs9.50\\bin\\";

            MagickNET.SetGhostscriptDirectory(ghostscriptLibraryPath);
            MagickNET.SetNativeLibraryDirectory(ghostscriptLibraryPath);
            MagickReadSettings settings = new MagickReadSettings()
            {
                Density = new Density(300, 300)
            };

            var bitmapImages = new List <System.Drawing.Bitmap>();

            using (MagickImageCollection images = new MagickImageCollection())
            {
                // Add all the pages of the pdf file to the collection
                images.Read(pdfStream, settings);                 //MagickImageCollection_ReadStream

                foreach (MagickImage image in images)
                {
                    bitmapImages.Add(image.ToBitmap());
                }
            }
            return(bitmapImages);
        }
 public void ShouldThrowExceptionWhenPathIsNull()
 {
     Assert.Throws <ArgumentNullException>("path", () =>
     {
         MagickNET.SetGhostscriptDirectory(null);
     });
 }
Exemple #3
0
        static void Main(string[] args)
        {
            MagickNET.SetLogEvents(LogEvents.All);
            MagickNET.Log += MagickNET_Log;
            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            MagickNET.SetGhostscriptDirectory(path);
            string fileName = Path.Combine(path, "480x600.jpg");

            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException("File not found", fileName);
            }
            string pdfFileName = Path.Combine(path, "test.pdf");

            if (File.Exists(pdfFileName))
            {
                File.Delete(pdfFileName);
            }
            using (var images = new MagickImageCollection()) {
                images.Add(new MagickImage(fileName));
                images.Write(pdfFileName);
                if (!File.Exists(pdfFileName))
                {
                    throw new FileNotFoundException("Pdf creation failed", pdfFileName);
                }
            }
        }
 public static void Initialize()
 {
     if (OperatingSystem.IsWindows)
     {
         MagickNET.SetGhostscriptDirectory(@"C:\Program Files (x86)\gs\gs9.53.1\bin");
     }
 }
 public void ShouldThrowExceptionWhenPathIsInvalid()
 {
     Assert.Throws <ArgumentException>("path", () =>
     {
         MagickNET.SetGhostscriptDirectory("Invalid");
     });
 }
        public static void Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log, ExecutionContext context)
        {
            log.Info("C# HTTP trigger function processed a request.");

            MagickNET.SetGhostscriptDirectory(context.FunctionAppDirectory);
            log.Info(context.FunctionAppDirectory);
            MagickReadSettings settings = new MagickReadSettings();

            // Settings the density to 300 dpi will create an image with a better quality
            settings.Density = new Density(300, 300);

            using (MagickImageCollection images = new MagickImageCollection())
            {
                log.Info(context.FunctionAppDirectory + "\\02.pdf");
                // Add all the pages of the pdf file to the collection
                images.Read(context.FunctionAppDirectory + "\\02.pdf", settings);

                int page = 1;
                foreach (MagickImage image in images)
                {
                    log.Info(context.FunctionAppDirectory + "\\outpng" + page + ".png");
                    // Write page to file that contains the page number
                    image.Write(context.FunctionAppDirectory + "\\outpng" + page + ".png");
                    // Writing to a specific format works the same as for a single image
                    //image.Format = MagickFormat.Ptif;
                    //image.Write(SampleFiles.OutputDirectory + "Snakeware.Page" + page + ".tif");
                    page++;
                }
            }

            log.Info("convert finish");
        }
        static MagickImageReader()
        {
            SupportedFormats = new[] { ".emf", ".eps", ".psd", ".svg", ".wmf", ".xps" };
            var currentPackageDir    = Path.GetDirectoryName(typeof(MagickImageReader).GetAssemblyLocalPath());
            var ghostscriptDirectory = Path.Combine(currentPackageDir, "Ghostscript");

            MagickNET.SetGhostscriptDirectory(ghostscriptDirectory);
        }
Exemple #8
0
        public PDFComicViewModel(string filePath) : base(filePath)
        {
            // if we're on Windows, use the included .dll and .exe files
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                MagickNET.SetGhostscriptDirectory(GhostscriptDirectoryWindows);
            }

            base.TotalPages = GetNumberOfPages();
        }
        public static void InitializeWithCustomPolicy(TestContext context)
        {
#if !NETCORE
            MagickNET.SetGhostscriptDirectory(@"C:\Program Files (x86)\gs\gs9.26\bin");
#endif

            ConfigurationFiles configFiles = ConfigurationFiles.Default;
            configFiles.Policy.Data = ModifyPolicy(configFiles.Policy.Data);

            _path = MagickNET.Initialize(configFiles);
        }
Exemple #10
0
        protected override void Initialize()
        {
            base.Initialize();

            string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            MagickNET.SetGhostscriptDirectory(applicationDirectory);

            this.isInputFilePdf = System.IO.Path.GetExtension(this.InputFilePath).ToLowerInvariant() == ".pdf";

            if (this.ConversionPreset == null)
            {
                throw new Exception("The conversion preset must be valid.");
            }
        }
        public IEnumerable <ITestCollection> OrderTestCollections(IEnumerable <ITestCollection> testCollections)
        {
#if !NETCORE
            MagickNET.SetGhostscriptDirectory(@"C:\Program Files (x86)\gs\gs9.53.1\bin");
#endif

            var configFiles = ConfigurationFiles.Default;
            configFiles.Policy.Data = ModifyPolicy(configFiles.Policy.Data);
            configFiles.Type.Data   = CreateTypeData();

            var path = Path.Combine(Path.GetTempPath(), "Magick.NET.Tests");
            Cleanup.DeleteDirectory(path);
            Directory.CreateDirectory(path);

            MagickNET.Initialize(configFiles, path);

            return(testCollections);
        }
        public void ConvertToScanned(string filename)
        {
            MagickReadSettings settings = new MagickReadSettings
            {
                Density = new Density(300, 300)
            };

            MagickNET.SetGhostscriptDirectory(Path.GetDirectoryName(GhostScriptHelper.GetGhostscriptVersion().DllPath));

            List <string> scannedimgfiles = new List <string>();

            using (MagickImageCollection images = new MagickImageCollection())
            {
                images.Read(filename, settings);

                int page = 1;

                foreach (MagickImage image in images)
                {
                    image.ColorSpace = ColorSpace.Gray;
                    var clone = image.Clone();
                    clone.Blur(0, 1);
                    clone.Compose = CompositeOperator.DivideDst;
                    image.Composite(clone);
                    image.LinearStretch(new Percentage(5), new Percentage(0));
                    image.Rotate(0.2);

                    var tempimgpath = Path.GetTempPath() + Path.GetFileNameWithoutExtension(filename) + "_img_" + page + ".png";
                    image.Write(tempimgpath);
                    scannedimgfiles.Add(tempimgpath);

                    page++;
                }
            }

            new ITextHelper().ImageToPdf(scannedimgfiles, filename);

            scannedimgfiles.ForEach(f => File.Delete(f));
        }
Exemple #13
0
        private string GerarImagem(Stream stream)
        {
            MagickNET.SetGhostscriptDirectory(Directory.GetCurrentDirectory());
            MagickNET.SetTempDirectory(Path.GetTempPath());

            var settings = new MagickReadSettings
            {
                Density = new Density(300, 300)
            };

            using (var images = new MagickImageCollection())
            {
                images.Read(stream, settings);

                using (var imagem = images.AppendHorizontally())
                {
                    var caminhoArquivo = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".png");
                    imagem.Format = MagickFormat.Png;
                    imagem.Write(caminhoArquivo);

                    return(caminhoArquivo);
                }
            }
        }
Exemple #14
0
        public ImageSource GetPage(string ghostScriptPath, string pdfFile, int pageNumber)
        {
            MagickNET.SetGhostscriptDirectory(ghostScriptPath);

            using (MagickImageCollection collection = new MagickImageCollection())
            {
                MagickReadSettings settings = new MagickReadSettings();
                settings.FrameIndex = pageNumber;

                settings.FrameCount = 1;

                try
                {
                    collection.Read(pdfFile, settings);
                }
                catch (MagickException)
                {
                    return(null);
                }


                return(SetBitmapImageFromBitmap(collection.ToBitmap(System.Drawing.Imaging.ImageFormat.Jpeg)));
            }
        }
Exemple #15
0
 public PreviewPDF()
 {
     InitializeComponent();
     MagickNET.SetGhostscriptDirectory(@"gs\");
 }
Exemple #16
0
        public static void PdfToImage()
        {
            /*
             * Ghostscript
             *
             * You only need to install Ghostscript if you want to convert EPS/PDF/PS files. Make sure you only install the version of
             * GhostScript with the same platform. If you use the 64-bit version of Magick.NET you should also install
             * the 64-bit version of Ghostscript.
             * You can use the 32-bit version together with the 64-version but you will get a better performance
             * if you keep the platforms the same.
             * Ghostscript can be downloaded here: http://www.ghostscript.com/download/gsdnld.html.
             *
             * If you don't want to install Ghostscript on your machine
             * you can copy gsdll32.dll/gsdl64.dll and gswin32c.exe/gswin64c.exe to your server
             * and tell Magick.NET where the file is located with the code below.
             *
             * MagickNET.SetGhostscriptDirectory(@"C:\MyProgram\Ghostscript");
             */

            // Assembly Absolute Path
            string assemblyFile = new Uri(Assembly.GetExecutingAssembly().CodeBase)
                                  .LocalPath;

            // Assembly folder name
            var path = Path.GetDirectoryName(assemblyFile);

            // Check for library
            if (!Directory.Exists(path))
            {
                throw new DirectoryNotFoundException("Impossibile trovare la directory dei files ghostscript");
            }

            MagickNET.SetGhostscriptDirectory(Path.Combine(path, "ghostscript"));

            MagickReadSettings settings = new MagickReadSettings();

            // Settings the density to 300 dpi will create an image with a better quality
            settings.Density = new Density(300, 300);

            using (MagickImageCollection images = new MagickImageCollection())
            {
                // Add all the pages of the pdf file to the collection
                images.Read(@"C:\tmp\doc.pdf", settings);

                int page = 1;
                foreach (MagickImage image in images)
                {
                    // resize
                    image.Resize(150, 150);

                    // Write page to file that contains the page number
                    image.Write("Snakeware.Page" + page + ".png");

                    // Writing to a specific format works the same as for a single image
                    //image.Format = MagickFormat.Ptif;
                    //image.Write("Snakeware.Page" + page + ".tif");
                    page++;

                    using (MemoryStream ms = new MemoryStream())
                    {
                        image.Write(ms);

                        var bytes = ms.ToArray();
                        Debug.WriteLine((int)bytes.Length / 1024);
                    }
                }
            }

            //using (MagickImage image = new MagickImage("gatto.jpg"))
            //{
            //    image.Resize(50, 50);
            //    FileInfo fi = new FileInfo(@"gatto_resize2.jpg");
            //    image.Write(fi);
            //}

            //using (MagickImage image = new MagickImage(@"C:\tmp\doc.pdf"))
            //{
            //    image.Write("test.pdf");
            //    //FileInfo fi = new FileInfo(@"gatto_resize2.jpg");
            //    //image.Write(fi);
            //}
        }
Exemple #17
0
 static ConvertisseurEpsVersTiff()
 {
     MagickNET.SetGhostscriptDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GS"));
 }
Exemple #18
0
 public static void Initialize()
 {
     MagickNET.SetGhostscriptDirectory(@"C:\Program Files (x86)\gs\gs9.18\bin");
 }
Exemple #19
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            if (req.Method != HttpMethod.Get)
            {
                //Send an Error if wrong HTTP method is used
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "This function currently only supports GET requests"));
            }

            // parse query parameter
            string pdfUrl = req.GetQueryNameValuePairs()
                            .FirstOrDefault(q => string.Compare(q.Key, "pdfurl", true) == 0)
                            .Value;

            if (pdfUrl == null)
            {
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "You need to provide a url via pdfurl option"));
            }

            log.Info("Got PDF Option. Downloading: " + pdfUrl);
            //Get PDF Document
            WebClient webClient = new WebClient();
            Stream    pdfStream = new MemoryStream(webClient.DownloadData(pdfUrl));

            //SetUp ImageMagick
            string ghostPath = $@"{AppFolder}\".Replace('\\', '/');
            var    debug     = Directory.GetFiles(ghostPath);

            log.Info("Setting up ImageMagick");

            foreach (var item in debug)
            {
                log.Info("Found file: " + item);
            }

            MagickNET.SetGhostscriptDirectory(ghostPath);
            MagickReadSettings settings = new MagickReadSettings();

            settings.Density = new Density(300, 300);

            //Convert PDF to JPG
            log.Info("Start converting");
            MemoryStream jpegStream = new MemoryStream();

            using (MagickImageCollection images = new MagickImageCollection())
            {
                images.Read(pdfStream, settings);
                foreach (MagickImage image in images)
                {
                    image.Format = MagickFormat.Jpeg;
                    image.Write(jpegStream);
                }
            }
            log.Info("Finished converting");

            //Create HTTP response
            log.Info("Creating response");
            var result = req.CreateResponse(HttpStatusCode.OK);

            result.Content = new ByteArrayContent(jpegStream.ToArray());
            result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
            return(result);
        }
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var currentDirectory = builder.Services.BuildServiceProvider()
                                   .GetService <IOptions <ExecutionContextOptions> >().Value.AppDirectory;

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(currentDirectory)
                                .AddJsonFile(@"appSettings.json", false, true)
                                .AddJsonFile(@"appSettings.Development.json", true, true)
                                .AddEnvironmentVariables()
                                .Build();

            if (configuration.GetValue <bool>("Ghostscript"))
            {
                var binDirectory    = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var ghostscriptPath = Path.Combine(binDirectory, "../Ghostscript");
                LogTo.Information("Setting Ghostscript path {0}", ghostscriptPath);
                MagickNET.SetGhostscriptDirectory(ghostscriptPath);
            }

            builder.Services.AddLogging();

            var account = new Account(
                configuration["cloudinary:name"],
                configuration["cloudinary:key"],
                configuration["cloudinary:secret"]);

            builder.Services.AddSingleton(new Cloudinary(account));

            builder.Services.AddTransient <ISourceContext>(provider => provider.GetService <SourceContext>());
            builder.Services.AddDbContext <SourceContext>(
                options => options.UseSqlServer(
                    configuration["wikibus:sources:sql"]));
            builder.Services.AddTransient <IImageStorage, CloudinaryImagesStore>();
            builder.Services.AddSingleton <IUriTemplateMatcher, DefaultUriTemplateMatcher>();
            builder.Services.AddSingleton <IUriTemplateExpander, DefaultUriTemplateExpander>();
            builder.Services.AddTransient <ISourceImageService, SourceImageService>();
            builder.Services.AddSingleton <IModelTemplateProvider, AttributeModelTemplateProvider>();
            builder.Services.AddSingleton <IBaseUriProvider, AppSettingsConfiguration>();
            builder.Services.AddTransient <ISourcesRepository, SourcesRepository>();
            builder.Services.AddTransient <EntityFactory>();
            builder.Services.AddSingleton <IWikibusConfiguration, AppSettingsConfiguration>();
            builder.Services.AddSingleton <IConfiguration>(configuration);
            builder.Services.AddSingleton <ISourcesDatabaseSettings, Settings>();
            builder.Services.AddSingleton <ICloudinarySettings, Settings>();
            builder.Services.AddSingleton <IAzureSettings, Settings>();
            builder.Services.AddSingleton <ManagementClientFactory>();
            builder.Services.AddScoped <ISourcesPersistence, SourcesPersistence>();
            builder.Services.AddScoped <IPdfService, PdfService>();
            builder.Services.AddScoped <IWishlistPersistence, WishlistPersistence>();

            if (configuration.IsDevelopment())
            {
                builder.Services.AddSingleton <IStorageQueue, NullStorageQueue>();
                builder.Services.AddSingleton <IFileStorage, LocalFileStorage>();
            }
            else
            {
                builder.Services.AddSingleton <IStorageQueue, StorageQueue>();
                builder.Services.AddSingleton <IFileStorage, BlobFileStorage>();
            }

            builder.Services.RegisterGoogleDrive(configuration);
        }
Exemple #21
0
 /// <summary>
 /// PdfToImage Startup
 /// </summary>
 public PdfToImage()
 {
     InitializeComponent();
     MagickNET.SetGhostscriptDirectory(String.Format(AppDomain.CurrentDomain.BaseDirectory + "PDFTools"));
 }
 public static void Initialize(TestContext context)
 {
     MagickNET.SetGhostscriptDirectory(@"C:\Program Files (x86)\gs\gs9.20\bin");
 }
Exemple #23
0
        public static void pdf2image(Guid applicationId,
                                     DocFileInfo pdf, string password, DocFileInfo destFile, ImageFormat imageFormat, bool repair)
        {
            //MagickNET.SetGhostscriptDirectory("[GhostScript DLL Dir]");
            //MagickNET.SetTempDirectory("[a temp dir]");

            if (!pdf.FileID.HasValue)
            {
                return;
            }
            else if (PDF2ImageProcessing.ContainsKey(pdf.FileID.Value) &&
                     (!repair || PDF2ImageProcessing[pdf.FileID.Value]))
            {
                return;
            }
            else
            {
                PDF2ImageProcessing[pdf.FileID.Value] = true;
            }

            if (destFile.file_exists_in_folder(applicationId) && !repair)
            {
                PDF2ImageProcessing[pdf.FileID.Value] = false;
                return;
            }

            try
            {
                string cacheDir = PublicMethods.map_path(PublicConsts.MagickCacheDirectory, localPath: true);
                if (!Directory.Exists(cacheDir))
                {
                    Directory.CreateDirectory(cacheDir);
                }
                MagickAnyCPU.CacheDirectory = cacheDir;
            }
            catch (Exception ex)
            {
                LogController.save_error_log(applicationId, null, "SetMagickCacheDirectory", ex, ModuleIdentifier.DCT);
            }

            try
            {
                string tempDir = PublicMethods.map_path(PublicConsts.TempDirectory, localPath: true);
                if (!Directory.Exists(tempDir))
                {
                    Directory.CreateDirectory(tempDir);
                }
                MagickNET.SetTempDirectory(tempDir);

                if (!string.IsNullOrEmpty(RaaiVanSettings.GhostScriptDirectory))
                {
                    MagickNET.SetGhostscriptDirectory(RaaiVanSettings.GhostScriptDirectory);
                }
            }
            catch (Exception ex)
            {
                LogController.save_error_log(applicationId, null, "SetMagickTempDirectory", ex, ModuleIdentifier.DCT);
            }

            try
            {
                using (MagickImageCollection pages = new MagickImageCollection())
                {
                    MagickReadSettings settings = new MagickReadSettings()
                    {
                        Density = new Density(100, 100)
                    };

                    bool invalidPassword = false;

                    using (PdfReader reader = PDFUtil.open_pdf_file(applicationId, pdf, password, ref invalidPassword))
                    {
                        byte[] pdfContent = PDFUtil.to_byte_array(reader);
                        pages.Read(pdfContent, settings);
                    }

                    int  pageNum    = 0;
                    bool errorLoged = false;

                    foreach (MagickImage p in pages)
                    {
                        ++pageNum;

                        destFile.FileName  = pageNum.ToString();
                        destFile.Extension = imageFormat.ToString().ToLower();

                        if (destFile.exists(applicationId))
                        {
                            continue;
                        }

                        try
                        {
                            using (MemoryStream stream = new MemoryStream())
                            {
                                p.ToBitmap(imageFormat).Save(stream, imageFormat);
                                destFile.store(applicationId, stream.ToArray());
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!errorLoged)
                            {
                                errorLoged = true;
                                LogController.save_error_log(applicationId, null,
                                                             "ConvertPDFPageToImage", ex, ModuleIdentifier.DCT);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogController.save_error_log(applicationId, null, "ConvertPDFToImage", ex, ModuleIdentifier.DCT);
            }

            PDF2ImageProcessing[pdf.FileID.Value] = false;
        }