コード例 #1
0
        static int Main(string[] args)
        {
            const int RET_OK  = 0;
            const int RET_ERR = 1;
            //Test();
            Options options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                if (options.Commands.Count == 0)
                {
                    Console.Write(options.GetUsage());
                    return(RET_OK);
                }

                try
                {
                    var cmd = options.Commands[0];
                    switch (cmd)
                    {
                    case "combine":
                    {
                        var files  = options.Input.Trim('\"').Split(',');
                        var output = options.Output.Trim('\"');
                        PdfOperations.Combine(files, output);
                        break;
                    }

                    case "barcode":
                    {
                        var    files   = options.Input.Trim('\"').Split(',');
                        var    output  = options.Output.Trim('\"');
                        var    code    = options.Code.Trim('\"');
                        string type    = options.Type.Trim('\"');
                        int    offsetX = options.OffsetX;
                        int    offsetY = options.OffsetY;
                        int    rotate  = options.Rotate;
                        //int type = !string.IsNullOrEmpty(options.Type) ? GetBarCodeType(options.Type) : iTextSharp.text.pdf.Barcode.EAN8;
                        //int offsetX = !string.IsNullOrEmpty(options.Type) ? GetBarCodeType(options.Type) : iTextSharp.text.pdf.Barcode.EAN8;
                        foreach (var file in files)
                        {
                            PdfOperations.BarcodeStamp(file, code, output, type, offsetX, offsetY, rotate);
                        }
                        break;
                    }

                    case "convert":
                    {
                        var input  = options.Input.Trim('\"');
                        var output = options.Output.Trim('\"');
                        PdfOperations.FromImage(input, output);
                        break;
                    }

                    case "image":
                    {
                        var input  = options.Input.Trim('\"');
                        var output = options.Output.Trim('\"');
                        var page   = options.Page;
                        PdfOperations.ToImage(input, page, output);
                        break;
                    }

                    case "scanbarcode":
                    {
                        var    input    = options.Input.Trim('\"');
                        var    page     = options.Page;
                        string barcode  = "";
                        string inputExt = System.IO.Path.GetExtension(input);
                        double scale    = options.Scale;
                        bool   noClean  = options.NoClean;

                        bool find = false;


                        if (inputExt == ".pdf")
                        {
                            PdfOperations.ToImage(input, page, input + ".png", (float)scale);
                            if (page == 0)
                            {
                                // All barcodes
                                Console.Write("Barcodes: ");
                                for (int i = 1; ; i++)
                                {
                                    string imageFileN = PdfOperations.GetFileNameWithIndex(input + ".png", i);
                                    if (!System.IO.File.Exists(imageFileN))
                                    {
                                        break;
                                    }
                                    barcode = BarcodeOperations.Scan(imageFileN);

                                    // Для не найденных barcode просто ставим ; чтобы можно было номер страницы сопоставить
                                    if (find == true)
                                    {
                                        Console.Write(";");
                                    }

                                    if (!string.IsNullOrEmpty(barcode))
                                    {
                                        Console.Write(barcode);
                                        find = true;
                                    }
                                    else
                                    {
                                        Console.Write("-");
                                    }

                                    if (!noClean)
                                    {
                                        System.IO.File.Delete(imageFileN);
                                    }
                                }
                                Console.WriteLine("");
                            }
                            else
                            {
                                barcode = BarcodeOperations.Scan(input + ".png");
                                if (!noClean)
                                {
                                    System.IO.File.Delete(input + ".png");
                                }
                                if (!string.IsNullOrEmpty(barcode))
                                {
                                    Console.WriteLine("Barcode: " + barcode);
                                    find = true;
                                }
                            }
                        }
                        else
                        {
                            barcode = BarcodeOperations.Scan(input);
                            if (!string.IsNullOrEmpty(barcode))
                            {
                                Console.WriteLine("Barcode: " + barcode);
                                find = true;
                            }
                        }

                        if (find == false)
                        {
                            Console.WriteLine(PdfOperations.BARCODE_NOT_FOUND);
                        }
                        break;
                    }

                    case "barcodereplace":
                    {
                        var input  = options.Input.Trim('\"');
                        var output = options.Output.Trim('\"');
                        if (input == output)
                        {
                            throw new Exception(PdfOperations.FILE_MUST_BE_DIFFERENT);
                        }
                        var  label           = options.Label;
                        var  code            = options.Code;
                        var  page            = options.Page;
                        bool displayText     = !options.NoText;
                        bool barCodeReplaced = PdfOperations.ReplaceBarcode128(input, output, page, label, code, displayText);
                        if (!barCodeReplaced)
                        {
                            Console.WriteLine(PdfOperations.BARCODE_NOT_FOUND);
                        }

                        break;
                    }

                    case "find":
                    {
                        var input = options.Input.Trim('\"');
                        var page  = options.Page;
                        var text  = options.Label;

                        var result = PdfOperations.SearchPdfFile(input, text, page);
                        if (result.Count > 0)
                        {
                            foreach (var item in result)
                            {
                                string pos = string.Format("Label position: {0}, {1}, {2}, {3} (page {4})", item.MinX, item.MinY, item.MaxX, item.MaxY, item.Page);
                                Console.WriteLine(pos);
                            }
                        }
                        else
                        {
                            Console.WriteLine(PdfOperations.LABEL_NOT_FOUND);
                        }
                        break;
                    }

                    case "barcodeonlabel":
                    {
                        string input  = options.Input.Trim('\"');
                        string output = options.Output.Trim('\"');
                        if (input == output)
                        {
                            throw new Exception(PdfOperations.FILE_MUST_BE_DIFFERENT);
                        }

                        string type        = options.Type.Trim('\"');
                        string code        = options.Code;
                        string text        = options.Label;
                        string widthParam  = options.Width;
                        string heightParam = options.Height;
                        bool   displayText = !options.NoText;
                        double barHeight   = options.BarHeight;

                        bool stampReplaced = PdfOperations.PlaceBarcodeOnLabel(input, output, text, type, code, widthParam, heightParam, (float)barHeight, displayText);
                        if (!stampReplaced)
                        {
                            Console.WriteLine(PdfOperations.LABEL_NOT_FOUND);
                        }

                        break;
                    }

                    case "imageonlabel":
                    {
                        string input     = options.Input.Trim('\"');
                        string output    = options.Output.Trim('\"');
                        string imageFile = options.ImageFile.Trim('\"');
                        if (input == output)
                        {
                            throw new Exception(PdfOperations.FILE_MUST_BE_DIFFERENT);
                        }

                        string label       = options.Label;
                        string widthParam  = options.Width;
                        string heightParam = options.Height;
                        bool   center      = options.Center;

                        bool labelFinded = PdfOperations.PlaceImageOnLabel(input, output, label, imageFile, widthParam, heightParam, center);
                        if (!labelFinded)
                        {
                            Console.WriteLine(PdfOperations.LABEL_NOT_FOUND);
                        }
                        break;
                    }

                    case "extractimages":
                    {
                        string input = options.Input.Trim('\"');
                        PdfOperations.ExtractImagesFromPDF(input);
                        break;
                    }

                    case "pagesizes":
                    {
                        string input = options.Input.Trim('\"');
                        IList <System.Drawing.SizeF> sizes = PdfOperations.GetPagesInfo(input);
                        bool firstTime = true;
                        foreach (System.Drawing.SizeF size in sizes)
                        {
                            if (!firstTime)
                            {
                                Console.Write(";");
                            }
                            Console.Write("{0};{1}", size.Width, size.Height);
                            firstTime = false;
                        }
                        Console.WriteLine();
                        break;
                    }

                    case "helloworld":
                    {
                        var output = options.Output;
                        if (string.IsNullOrEmpty(output))
                        {
                            output = "helloworld.pdf";
                        }
                        else
                        {
                            output = output.Trim('\"');
                        }
                        PdfOperations.HelloWorld(output);
                        break;
                    }
                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(PdfOperations.OPERATION_ERROR);
                    Console.WriteLine(ex.Message);
                    return(RET_ERR);
                }
                return(RET_OK);
            }
            return(RET_ERR);
        }
コード例 #2
0
        static public bool ReplaceBarcode128(string input, string output, int page, string sourceCode, string newCode, bool displayText, int maxBarCodeCount = 5)
        {
            float scale = 3;
            float dpi   = 300;

            bool barCodeFinded = false;

            Barcode       barcodeNew = CreateBarcode(BarcodeType.Code128, newCode, displayText);
            BarcodeResult barcode    = null;

            using (var fs = new FileStream(output, FileMode.Create))
                using (var pdfReader = new iTextSharp.text.pdf.PdfReader(input))
                    using (var document = PdfiumViewer.PdfDocument.Load(input))
                    {
                        PdfStamper stamper = new PdfStamper(pdfReader, fs);

                        var           info  = document.GetInformation();
                        IList <SizeF> sizes = document.PageSizes;

                        // Если задана страница, то только в нёё вставим штрихкод, если не задана, то для всех страниц документа
                        int count;
                        if (page <= 0)
                        {
                            page  = 0;
                            count = document.PageCount;
                        }
                        else
                        {
                            // В Pdfium нумерация с 0-ля, а у нас приходит с 1-цы.
                            count = page;
                            page -= 1;
                        }
                        for (; page < count; page++)
                        {
                            int imageWidth           = (int)(sizes[page].Width * scale);
                            int imageHeight          = (int)(sizes[page].Height * scale);
                            System.Drawing.Image img = document.Render(page, imageWidth, imageHeight, dpi, dpi, PdfiumViewer.PdfRenderFlags.Grayscale);

                            for (int i = 0; i < maxBarCodeCount; i++)
                            {
                                barcode = BarcodeOperations.ScanCode128(img, input + ".png");
                                if (barcode != null)
                                {
                                    barCodeFinded = true;
                                    if (barcode.Code == sourceCode)
                                    {
                                        float offsetX       = barcode.Left / scale;
                                        float offsetY       = barcode.Top / scale;
                                        float width         = (barcode.Right - barcode.Left) / scale;
                                        float rotateDegrees = barcode.Orientation;

                                        // Преобразуем к 0-360 и уберем минимальные отклонения
                                        // if (rotateDegrees < 0) rotateDegrees += 360;
                                        // else if (rotateDegrees >= 360) rotateDegrees -= 360;
                                        // if (Math.Abs(rotateDegrees - 0) <= 4) rotateDegrees = 0;
                                        // if (Math.Abs(rotateDegrees - 90) <= 4) rotateDegrees = 90;
                                        // if (Math.Abs(rotateDegrees - 180) <= 4) rotateDegrees = 180;
                                        // if (Math.Abs(rotateDegrees - 270) <= 4) rotateDegrees = 270;

                                        iTextSharp.text.Rectangle pagesize = pdfReader.GetPageSizeWithRotation(page + 1);

                                        // Поскольку ось координат Y для img,bmp сверху вниз направлена и начало в верхнем левом угле,
                                        // а в pdf снизу вверх и в нижним левом угле, то преобразуем координаты
                                        offsetY       = pagesize.Height - offsetY;
                                        rotateDegrees = -rotateDegrees;

                                        PdfOperations.PlaceBarcode(stamper, barcodeNew, page + 1, offsetX, offsetY, width, rotateDegrees);
                                    }
                                    else
                                    {
                                        Console.WriteLine(BARCODE_DIFFERENT_FOUND + barcode.Code);
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        stamper.Close();
                    }

            return(barCodeFinded);
        }