Beispiel #1
0
// ---------------------------------------------------------------------------

        /**
         * Generates a PDF file with the text 'Hello World'
         */
        public byte[] CreatePdf()
        {
            using (MemoryStream ms = new MemoryStream()) {
                using (Document document = new Document()) {
                    // step 2
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    // step 3
                    document.Open();
                    // step 4
                    // we add the text to the direct content, but not in the right order
                    PdfContentByte cb = writer.DirectContent;
                    BaseFont       bf = BaseFont.CreateFont();
                    cb.BeginText();
                    cb.SetFontAndSize(bf, 12);
                    cb.MoveText(88.66f, 367);
                    cb.ShowText("ld");
                    cb.MoveText(-22f, 0);
                    cb.ShowText("Wor");
                    cb.MoveText(-15.33f, 0);
                    cb.ShowText("llo");
                    cb.MoveText(-15.33f, 0);
                    cb.ShowText("He");
                    cb.EndText();
                    // we also add text in a form XObject
                    PdfTemplate tmp = cb.CreateTemplate(250, 25);
                    tmp.BeginText();
                    tmp.SetFontAndSize(bf, 12);
                    tmp.MoveText(0, 7);
                    tmp.ShowText("Hello People");
                    tmp.EndText();
                    cb.AddTemplate(tmp, 36, 343);
                }
                return(ms.ToArray());
            }
        }
Beispiel #2
0
        public void CreatePdfAbsolute()
        {
            // step 1
            Document document = new Document();

            Document.Compress = false;
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(RESULT_ABSOLUTE, FileMode.Create));

            //writer.setCompressionLevel(PdfStream.NO_COMPRESSION);
            // step 3
            document.Open();
            // step 4
            PdfContentByte canvas = writer.DirectContentUnder;

            writer.CompressionLevel = 0;
            canvas.SaveState();                               // q
            canvas.BeginText();                               // BT
            canvas.MoveText(36, 788);                         // 36 788 Td
            canvas.SetFontAndSize(BaseFont.CreateFont(), 12); // /F1 12 Tf
            canvas.ShowText("Hel");                           // (Hel)Tj
            canvas.MoveText(30.65f, 0);
            canvas.ShowText("World!");                        // (World!)Tj
            canvas.MoveText(-12.7f, 0);
            canvas.ShowText("lo");                            // (lo)Tj
            canvas.EndText();                                 // ET
            canvas.RestoreState();                            // Q
            // step 5
            document.Close();
            Document.Compress = true;
        }
 public void Run()
 {
     try {
         PdfReader reader =
             new PdfReader(File.Open(TEST_RESOURCES_PATH + "test.pdf", FileMode.Open, FileAccess.Read,
                                     FileShare.Read));
         PdfStamper stamper = new PdfStamper(reader,
                                             new FileStream(TARGET_PATH + "out" + threadNumber + ".pdf", FileMode.Create));
         PdfContentByte cb = stamper.GetOverContent(1);
         cb.BeginText();
         BaseFont font = BaseFont.CreateFont(TEST_RESOURCES_PATH + "FreeSans.ttf",
                                             threadNumber % 2 == 0 ? BaseFont.IDENTITY_H : BaseFont.WINANSI, BaseFont.EMBEDDED);
         cb.SetFontAndSize(font, 12);
         cb.MoveText(30, 600);
         cb.ShowText("`1234567890-=qwertyuiop[]asdfghjkl;'\\zxcvbnm,./");
         cb.EndText();
         stamper.Close();
         reader.Close();
     }
     catch (Exception exc) {
         RegisterException(threadNumber, exc);
     }
     finally {
         latch.Decrement();
     }
 }
        public void Verify_HelloWorldDirect_CanBeCreated()
        {
            var pdfFilePath = TestUtils.GetOutputFileName();
            var stream      = new FileStream(pdfFilePath, FileMode.Create);

            // step 1
            var document = new Document();

            // step 2
            var writer = PdfWriter.GetInstance(document, stream);

            // step 3
            document.AddAuthor(TestUtils.Author);
            document.Open();
            // step 4
            PdfContentByte canvas = writer.DirectContentUnder;

            writer.CompressionLevel = 0;
            canvas.SaveState();                               // q
            canvas.BeginText();                               // BT
            canvas.MoveText(36, 788);                         // 36 788 Td
            canvas.SetFontAndSize(BaseFont.CreateFont(), 12); // /F1 12 Tf
            canvas.ShowText("HelloWorldDirect");              // (Hello World)Tj
            canvas.EndText();                                 // ET
            canvas.RestoreState();                            // Q

            document.Close();
            stream.Dispose();

            TestUtils.VerifyPdfFileIsReadable(pdfFilePath);
        }
        private byte[] CreatePdfWithNegativeCharSpacing(String str1, float charSpacing, String str2)
        {
            MemoryStream baos   = new MemoryStream();
            Document     doc    = new Document();
            PdfWriter    writer = PdfWriter.GetInstance(doc, baos);

            writer.CompressionLevel = 0;
            doc.Open();

            PdfContentByte canvas = writer.DirectContent;

            canvas.BeginText();
            canvas.SetFontAndSize(BaseFont.CreateFont(), 12);
            canvas.MoveText(45, doc.PageSize.Height - 45);
            PdfTextArray ta = new PdfTextArray();

            ta.Add(str1);
            ta.Add(charSpacing);
            ta.Add(str2);
            canvas.ShowText(ta);
            canvas.EndText();

            doc.Close();

            return(baos.ToArray());
        }
Beispiel #6
0
        public void Td(Int64 x, Int64 y)
        {
            m_canvas.MoveText(
                (float)(dkw(x) - dkw(m_last_td_x)),
                (float)(dkh(y) - dkh(m_last_td_y))
                );

            m_last_td_x = x;
            m_last_td_y = y;
        }
Beispiel #7
0
        private static byte[] CreatePdfWithRotatedText(String text1, String text2, float rotation, bool moveTextToNextLine, float moveTextDelta)
        {
            MemoryStream byteStream = new MemoryStream();

            Document  document = new Document();
            PdfWriter writer   = PdfWriter.GetInstance(document, byteStream);

            document.SetPageSize(PageSize.LETTER);

            document.Open();

            PdfContentByte cb = writer.DirectContent;

            BaseFont font = BaseFont.CreateFont();

            float x = document.PageSize.Width / 2;
            float y = document.PageSize.Height / 2;

            Matrix matrix = new Matrix();

            matrix.Translate(x, y);
            cb.Transform(matrix);

            cb.MoveTo(-10, 0);
            cb.LineTo(10, 0);
            cb.MoveTo(0, -10);
            cb.LineTo(0, 10);
            cb.Stroke();

            cb.BeginText();
            cb.SetFontAndSize(font, 12);
            matrix = new Matrix();
            matrix.Rotate(rotation);
            cb.Transform(matrix);
            cb.ShowText(text1);
            if (moveTextToNextLine)
            {
                cb.MoveText(0, moveTextDelta);
            }
            else
            {
                matrix = new Matrix();
                matrix.Translate(moveTextDelta, 0);
                cb.Transform(matrix);
            }
            cb.ShowText(text2);
            cb.EndText();

            document.Close();

            byte[] pdfBytes = byteStream.ToArray();

            return(pdfBytes);
        }
        public void Test_Draw_Text()
        {
            var pdfFilePath = TestUtils.GetOutputFileName();
            var fileStream  = new FileStream(pdfFilePath, FileMode.Create);
            var pdfDoc      = new Document(PageSize.A4);
            var pdfWriter   = PdfWriter.GetInstance(pdfDoc, fileStream);

            pdfDoc.AddAuthor(TestUtils.Author);
            pdfDoc.Open();

            pdfDoc.Add(new Paragraph("Test"));

            PdfContentByte cb = pdfWriter.DirectContent;
            BaseFont       bf = BaseFont.CreateFont();

            cb.BeginText();
            cb.SetFontAndSize(bf, 12);
            cb.MoveText(88.66f, 367);
            cb.ShowText("ld");
            cb.MoveText(-22f, 0);
            cb.ShowText("Wor");
            cb.MoveText(-15.33f, 0);
            cb.ShowText("llo");
            cb.MoveText(-15.33f, 0);
            cb.ShowText("He");
            cb.EndText();

            PdfTemplate tmp = cb.CreateTemplate(250, 25);

            tmp.BeginText();
            tmp.SetFontAndSize(bf, 12);
            tmp.MoveText(0, 7);
            tmp.ShowText("Hello People");
            tmp.EndText();
            cb.AddTemplate(tmp, 36, 343);

            pdfDoc.Close();
            fileStream.Dispose();

            TestUtils.VerifyPdfFileIsReadable(pdfFilePath);
        }
        private byte[] CreatePdfWithFontSpacingEqualsCharSpacing()
        {
            MemoryStream baos   = new MemoryStream();
            Document     doc    = new Document();
            PdfWriter    writer = PdfWriter.GetInstance(doc, baos);

            doc.Open();

            BaseFont font      = BaseFont.CreateFont();
            int      fontSize  = 12;
            float    charSpace = font.GetWidth(' ') / 1000.0f;

            PdfContentByte canvas = writer.DirectContent;

            canvas.BeginText();
            canvas.SetFontAndSize(font, fontSize);
            canvas.MoveText(45, doc.PageSize.Height - 45);
            canvas.SetCharacterSpacing(-charSpace * fontSize);

            PdfTextArray textArray = new PdfTextArray();

            textArray.Add("P");
            textArray.Add(-226.2f);
            textArray.Add("r");
            textArray.Add(-231.8f);
            textArray.Add("e");
            textArray.Add(-230.8f);
            textArray.Add("f");
            textArray.Add(-238);
            textArray.Add("a");
            textArray.Add(-238.9f);
            textArray.Add("c");
            textArray.Add(-228.9f);
            textArray.Add("e");

            canvas.ShowText(textArray);
            canvas.EndText();

            doc.Close();

            byte[] pdfBytes = baos.ToArray();

            return(pdfBytes);
        }
Beispiel #10
0
// ===========================================================================
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                var writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                PdfContentByte canvas = writer.DirectContentUnder;
                writer.CompressionLevel = 0;
                canvas.SaveState();                               // q
                canvas.BeginText();                               // BT
                canvas.MoveText(36, 788);                         // 36 788 Td
                canvas.SetFontAndSize(BaseFont.CreateFont(), 12); // /F1 12 Tf
                canvas.ShowText("HelloWorldDirect");              // (Hello World)Tj
                canvas.EndText();                                 // ET
                canvas.RestoreState();                            // Q
            }
        }
        private byte[] CreatePdfWithLittleFontSize()
        {
            MemoryStream baos   = new MemoryStream();
            Document     doc    = new Document();
            PdfWriter    writer = PdfWriter.GetInstance(doc, baos);

            doc.Open();

            BaseFont       font   = BaseFont.CreateFont();
            PdfContentByte canvas = writer.DirectContent;

            canvas.BeginText();
            canvas.SetFontAndSize(font, 0.2f);
            canvas.MoveText(45, doc.PageSize.Height - 45);

            PdfTextArray textArray = new PdfTextArray();

            textArray.Add("P");
            textArray.Add("r");
            textArray.Add("e");
            textArray.Add("f");
            textArray.Add("a");
            textArray.Add("c");
            textArray.Add("e");
            textArray.Add(" ");

            canvas.ShowText(textArray);
            canvas.SetFontAndSize(font, 10);
            canvas.ShowText(textArray);

            canvas.EndText();

            doc.Close();

            byte[] pdfBytes = baos.ToArray();

            return(pdfBytes);
        }
Beispiel #12
0
        public void CreatePdfLow()
        {
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(RESULT_LOW, FileMode.Create));

            writer.CompressionLevel = PdfStream.NO_COMPRESSION;
            // step 3
            document.Open();
            // step 4
            PdfContentByte canvas = writer.DirectContentUnder;

            canvas.SaveState();                               // q
            canvas.BeginText();                               // BT
            canvas.MoveText(36, 788);                         // 36 788 Td
            canvas.SetFontAndSize(BaseFont.CreateFont(), 12); // /F1 12 Tf
            canvas.ShowText("Hello World!");                  // (Hello World!)Tj
            canvas.EndText();                                 // ET
            canvas.RestoreState();                            // Q
            // step 5
            document.Close();
        }
Beispiel #13
0
        /**
        * Writes a text line to the document. It takes care of all the attributes.
        * <P>
        * Before entering the line position must have been established and the
        * <CODE>text</CODE> argument must be in text object scope (<CODE>beginText()</CODE>).
        * @param line the line to be written
        * @param text the <CODE>PdfContentByte</CODE> where the text will be written to
        * @param graphics the <CODE>PdfContentByte</CODE> where the graphics will be written to
        * @param currentValues the current font and extra spacing values
        * @param ratio
        * @throws DocumentException on error
        */
        internal void WriteLineToContent(PdfLine line, PdfContentByte text, PdfContentByte graphics, Object[] currentValues, float ratio)
        {
            PdfFont currentFont = (PdfFont)(currentValues[0]);
            float lastBaseFactor = (float)currentValues[1];
            //PdfChunk chunkz;
            int numberOfSpaces;
            int lineLen;
            bool isJustified;
            float hangingCorrection = 0;
            float hScale = 1;
            float lastHScale = float.NaN;
            float baseWordSpacing = 0;
            float baseCharacterSpacing = 0;
            float glueWidth = 0;

            numberOfSpaces = line.NumberOfSpaces;
            lineLen = line.GetLineLengthUtf32();
            // does the line need to be justified?
            isJustified = line.HasToBeJustified() && (numberOfSpaces != 0 || lineLen > 1);
            int separatorCount = line.GetSeparatorCount();
            if (separatorCount > 0) {
                glueWidth = line.WidthLeft / separatorCount;
            }
            else if (isJustified) {
                if (line.NewlineSplit && line.WidthLeft >= (lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1))) {
                    if (line.RTL) {
                        text.MoveText(line.WidthLeft - lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1), 0);
                    }
                    baseWordSpacing = ratio * lastBaseFactor;
                    baseCharacterSpacing = lastBaseFactor;
                }
                else {
                    float width = line.WidthLeft;
                    PdfChunk last = line.GetChunk(line.Size - 1);
                    if (last != null) {
                        String s = last.ToString();
                        char c;
                        if (s.Length > 0 && hangingPunctuation.IndexOf((c = s[s.Length - 1])) >= 0) {
                            float oldWidth = width;
                            width += last.Font.Width(c) * 0.4f;
                            hangingCorrection = width - oldWidth;
                        }
                    }
                    float baseFactor = width / (ratio * numberOfSpaces + lineLen - 1);
                    baseWordSpacing = ratio * baseFactor;
                    baseCharacterSpacing = baseFactor;
                    lastBaseFactor = baseFactor;
                }
            }

            int lastChunkStroke = line.LastStrokeChunk;
            int chunkStrokeIdx = 0;
            float xMarker = text.XTLM;
            float baseXMarker = xMarker;
            float yMarker = text.YTLM;
            bool adjustMatrix = false;
            float tabPosition = 0;

            // looping over all the chunks in 1 line
            foreach (PdfChunk chunk in line) {
                Color color = chunk.Color;
                hScale = 1;

                if (chunkStrokeIdx <= lastChunkStroke) {
                    float width;
                    if (isJustified) {
                        width = chunk.GetWidthCorrected(baseCharacterSpacing, baseWordSpacing);
                    }
                    else {
                        width = chunk.Width;
                    }
                    if (chunk.IsStroked()) {
                        PdfChunk nextChunk = line.GetChunk(chunkStrokeIdx + 1);
                        if (chunk.IsSeparator()) {
                            width = glueWidth;
                            Object[] sep = (Object[])chunk.GetAttribute(Chunk.SEPARATOR);
                            IDrawInterface di = (IDrawInterface)sep[0];
                            bool vertical = (bool)sep[1];
                            float fontSize = chunk.Font.Size;
                            float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize);
                            float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize);
                            if (vertical) {
                                di.Draw(graphics, baseXMarker, yMarker + descender, baseXMarker + line.OriginalWidth, ascender - descender, yMarker);
                            }
                            else {
                                di.Draw(graphics, xMarker, yMarker + descender, xMarker + width, ascender - descender, yMarker);
                            }
                        }
                        if (chunk.IsTab()) {
                            Object[] tab = (Object[])chunk.GetAttribute(Chunk.TAB);
                            IDrawInterface di = (IDrawInterface)tab[0];
                            tabPosition = (float)tab[1] + (float)tab[3];
                            float fontSize = chunk.Font.Size;
                            float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize);
                            float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize);
                            if (tabPosition > xMarker) {
                                di.Draw(graphics, xMarker, yMarker + descender, tabPosition, ascender - descender, yMarker);
                            }
                            float tmp = xMarker;
                            xMarker = tabPosition;
                            tabPosition = tmp;
                        }
                        if (chunk.IsAttribute(Chunk.BACKGROUND)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.BACKGROUND))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            float fontSize = chunk.Font.Size;
                            float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize);
                            float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize);
                            Object[] bgr = (Object[])chunk.GetAttribute(Chunk.BACKGROUND);
                            graphics.SetColorFill((Color)bgr[0]);
                            float[] extra = (float[])bgr[1];
                            graphics.Rectangle(xMarker - extra[0],
                                yMarker + descender - extra[1] + chunk.TextRise,
                                width - subtract + extra[0] + extra[2],
                                ascender - descender + extra[1] + extra[3]);
                            graphics.Fill();
                            graphics.SetGrayFill(0);
                        }
                        if (chunk.IsAttribute(Chunk.UNDERLINE)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.UNDERLINE))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            Object[][] unders = (Object[][])chunk.GetAttribute(Chunk.UNDERLINE);
                            Color scolor = null;
                            for (int k = 0; k < unders.Length; ++k) {
                                Object[] obj = unders[k];
                                scolor = (Color)obj[0];
                                float[] ps = (float[])obj[1];
                                if (scolor == null)
                                    scolor = color;
                                if (scolor != null)
                                    graphics.SetColorStroke(scolor);
                                float fsize = chunk.Font.Size;
                                graphics.SetLineWidth(ps[0] + fsize * ps[1]);
                                float shift = ps[2] + fsize * ps[3];
                                int cap2 = (int)ps[4];
                                if (cap2 != 0)
                                    graphics.SetLineCap(cap2);
                                graphics.MoveTo(xMarker, yMarker + shift);
                                graphics.LineTo(xMarker + width - subtract, yMarker + shift);
                                graphics.Stroke();
                                if (scolor != null)
                                    graphics.ResetGrayStroke();
                                if (cap2 != 0)
                                    graphics.SetLineCap(0);
                            }
                            graphics.SetLineWidth(1);
                        }
                        if (chunk.IsAttribute(Chunk.ACTION)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.ACTION))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            text.AddAnnotation(new PdfAnnotation(writer, xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size, (PdfAction)chunk.GetAttribute(Chunk.ACTION)));
                        }
                        if (chunk.IsAttribute(Chunk.REMOTEGOTO)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.REMOTEGOTO))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            Object[] obj = (Object[])chunk.GetAttribute(Chunk.REMOTEGOTO);
                            String filename = (String)obj[0];
                            if (obj[1] is String)
                                RemoteGoto(filename, (String)obj[1], xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size);
                            else
                                RemoteGoto(filename, (int)obj[1], xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size);
                        }
                        if (chunk.IsAttribute(Chunk.LOCALGOTO)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.LOCALGOTO))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            LocalGoto((String)chunk.GetAttribute(Chunk.LOCALGOTO), xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size);
                        }
                        if (chunk.IsAttribute(Chunk.LOCALDESTINATION)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.LOCALDESTINATION))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            LocalDestination((String)chunk.GetAttribute(Chunk.LOCALDESTINATION), new PdfDestination(PdfDestination.XYZ, xMarker, yMarker + chunk.Font.Size, 0));
                        }
                        if (chunk.IsAttribute(Chunk.GENERICTAG)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.GENERICTAG))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            Rectangle rect = new Rectangle(xMarker, yMarker, xMarker + width - subtract, yMarker + chunk.Font.Size);
                            IPdfPageEvent pev = writer.PageEvent;
                            if (pev != null)
                                pev.OnGenericTag(writer, this, rect, (String)chunk.GetAttribute(Chunk.GENERICTAG));
                        }
                        if (chunk.IsAttribute(Chunk.PDFANNOTATION)) {
                            float subtract = lastBaseFactor;
                            if (nextChunk != null && nextChunk.IsAttribute(Chunk.PDFANNOTATION))
                                subtract = 0;
                            if (nextChunk == null)
                                subtract += hangingCorrection;
                            float fontSize = chunk.Font.Size;
                            float ascender = chunk.Font.Font.GetFontDescriptor(BaseFont.ASCENT, fontSize);
                            float descender = chunk.Font.Font.GetFontDescriptor(BaseFont.DESCENT, fontSize);
                            PdfAnnotation annot = PdfFormField.ShallowDuplicate((PdfAnnotation)chunk.GetAttribute(Chunk.PDFANNOTATION));
                            annot.Put(PdfName.RECT, new PdfRectangle(xMarker, yMarker + descender, xMarker + width - subtract, yMarker + ascender));
                            text.AddAnnotation(annot);
                        }
                        float[] paramsx = (float[])chunk.GetAttribute(Chunk.SKEW);
                        object hs = chunk.GetAttribute(Chunk.HSCALE);
                        if (paramsx != null || hs != null) {
                            float b = 0, c = 0;
                            if (paramsx != null) {
                                b = paramsx[0];
                                c = paramsx[1];
                            }
                            if (hs != null)
                                hScale = (float)hs;
                            text.SetTextMatrix(hScale, b, c, 1, xMarker, yMarker);
                        }
                        if (chunk.IsImage()) {
                            Image image = chunk.Image;
                            float[] matrix = image.Matrix;
                            matrix[Image.CX] = xMarker + chunk.ImageOffsetX - matrix[Image.CX];
                            matrix[Image.CY] = yMarker + chunk.ImageOffsetY - matrix[Image.CY];
                            graphics.AddImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
                            text.MoveText(xMarker + lastBaseFactor + image.ScaledWidth - text.XTLM, 0);
                        }
                    }
                    xMarker += width;
                    ++chunkStrokeIdx;
                }

                if (chunk.Font.CompareTo(currentFont) != 0) {
                    currentFont = chunk.Font;
                    text.SetFontAndSize(currentFont.Font, currentFont.Size);
                }
                float rise = 0;
                Object[] textRender = (Object[])chunk.GetAttribute(Chunk.TEXTRENDERMODE);
                int tr = 0;
                float strokeWidth = 1;
                Color strokeColor = null;
                object fr = chunk.GetAttribute(Chunk.SUBSUPSCRIPT);
                if (textRender != null) {
                    tr = (int)textRender[0] & 3;
                    if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL)
                        text.SetTextRenderingMode(tr);
                    if (tr == PdfContentByte.TEXT_RENDER_MODE_STROKE || tr == PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE) {
                        strokeWidth = (float)textRender[1];
                        if (strokeWidth != 1)
                            text.SetLineWidth(strokeWidth);
                        strokeColor = (Color)textRender[2];
                        if (strokeColor == null)
                            strokeColor = color;
                        if (strokeColor != null)
                            text.SetColorStroke(strokeColor);
                    }
                }
                if (fr != null)
                    rise = (float)fr;
                if (color != null)
                    text.SetColorFill(color);
                if (rise != 0)
                    text.SetTextRise(rise);
                if (chunk.IsImage()) {
                    adjustMatrix = true;
                }
                else if (chunk.IsHorizontalSeparator()) {
                    PdfTextArray array = new PdfTextArray();
                    array.Add(-glueWidth * 1000f / chunk.Font.Size / hScale);
                    text.ShowText(array);
                }
                else if (chunk.IsTab()) {
                    PdfTextArray array = new PdfTextArray();
                    array.Add((tabPosition - xMarker) * 1000f / chunk.Font.Size / hScale);
                    text.ShowText(array);
                }
                // If it is a CJK chunk or Unicode TTF we will have to simulate the
                // space adjustment.
                else if (isJustified && numberOfSpaces > 0 && chunk.IsSpecialEncoding()) {
                    if (hScale != lastHScale) {
                        lastHScale = hScale;
                        text.SetWordSpacing(baseWordSpacing / hScale);
                        text.SetCharacterSpacing(baseCharacterSpacing / hScale);
                    }
                    String s = chunk.ToString();
                    int idx = s.IndexOf(' ');
                    if (idx < 0)
                        text.ShowText(s);
                    else {
                        float spaceCorrection = - baseWordSpacing * 1000f / chunk.Font.Size / hScale;
                        PdfTextArray textArray = new PdfTextArray(s.Substring(0, idx));
                        int lastIdx = idx;
                        while ((idx = s.IndexOf(' ', lastIdx + 1)) >= 0) {
                            textArray.Add(spaceCorrection);
                            textArray.Add(s.Substring(lastIdx, idx - lastIdx));
                            lastIdx = idx;
                        }
                        textArray.Add(spaceCorrection);
                        textArray.Add(s.Substring(lastIdx));
                        text.ShowText(textArray);
                    }
                }
                else {
                    if (isJustified && hScale != lastHScale) {
                        lastHScale = hScale;
                        text.SetWordSpacing(baseWordSpacing / hScale);
                        text.SetCharacterSpacing(baseCharacterSpacing / hScale);
                    }
                    text.ShowText(chunk.ToString());
                }

                if (rise != 0)
                    text.SetTextRise(0);
                if (color != null)
                    text.ResetRGBColorFill();
                if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL)
                    text.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
                if (strokeColor != null)
                    text.ResetRGBColorStroke();
                if (strokeWidth != 1)
                    text.SetLineWidth(1);
                if (chunk.IsAttribute(Chunk.SKEW) || chunk.IsAttribute(Chunk.HSCALE)) {
                    adjustMatrix = true;
                    text.SetTextMatrix(xMarker, yMarker);
                }
            }
            if (isJustified) {
                text.SetWordSpacing(0);
                text.SetCharacterSpacing(0);
                if (line.NewlineSplit)
                    lastBaseFactor = 0;
            }
            if (adjustMatrix)
                text.MoveText(baseXMarker - text.XTLM, 0);
            currentValues[0] = currentFont;
            currentValues[1] = lastBaseFactor;
        }
Beispiel #14
0
// ===========================================================================
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                PdfContentByte canvas = writer.DirectContent;
                String         text   = "AWAY again";
                BaseFont       bf     = BaseFont.CreateFont();
                canvas.BeginText();
                // line 1
                canvas.SetFontAndSize(bf, 16);
                canvas.MoveText(36, 806);
                canvas.MoveTextWithLeading(0, -24);
                canvas.ShowText(text);
                // line 2
                canvas.SetWordSpacing(20);
                canvas.NewlineShowText(text);
                // line 3
                canvas.SetCharacterSpacing(10);
                canvas.NewlineShowText(text);
                canvas.SetWordSpacing(0);
                canvas.SetCharacterSpacing(0);
                // line 4
                canvas.SetHorizontalScaling(50);
                canvas.NewlineShowText(text);
                canvas.SetHorizontalScaling(100);
                // line 5
                canvas.NewlineShowText(text);
                canvas.SetTextRise(15);
                canvas.SetFontAndSize(bf, 12);
                canvas.SetColorFill(BaseColor.RED);
                canvas.ShowText("2");
                canvas.SetColorFill(GrayColor.GRAYBLACK);
                // line 6
                canvas.SetLeading(56);
                canvas.NewlineShowText("Changing the leading: " + text);
                canvas.SetLeading(24);
                canvas.NewlineText();
                // line 7
                PdfTextArray array = new PdfTextArray("A");
                array.Add(120);
                array.Add("W");
                array.Add(120);
                array.Add("A");
                array.Add(95);
                array.Add("Y again");
                canvas.ShowText(array);
                canvas.EndText();

                canvas.SetColorFill(BaseColor.BLUE);
                canvas.BeginText();
                canvas.SetTextMatrix(360, 770);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();

                canvas.BeginText();
                canvas.SetTextMatrix(360, 730);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();

                canvas.BeginText();
                canvas.SetTextMatrix(360, 690);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();

                canvas.BeginText();
                canvas.SetTextMatrix(360, 650);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();

                PdfTemplate template = canvas.CreateTemplate(200, 36);
                template.SetLineWidth(2);
                for (int i = 0; i < 6; i++)
                {
                    template.MoveTo(0, i * 6);
                    template.LineTo(200, i * 6);
                }
                template.Stroke();

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetTextMatrix(360, 610);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_CLIP);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();
                canvas.AddTemplate(template, 360, 610);
                canvas.RestoreState();

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetTextMatrix(360, 570);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE_CLIP);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();
                canvas.AddTemplate(template, 360, 570);
                canvas.RestoreState();

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetTextMatrix(360, 530);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE_CLIP);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();
                canvas.AddTemplate(template, 360, 530);
                canvas.RestoreState();

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetTextMatrix(360, 490);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_CLIP);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();
                canvas.AddTemplate(template, 360, 490);
                canvas.RestoreState();
            }
        }
Beispiel #15
0
        public void createPrintDocPDF(int Order_Id)
        {
            List <ProductsModel> lsProductReport = new List <ProductsModel>();
            Rectangle            rec             = new Rectangle(PageSize.A4);
            Document             doc             = new Document(rec, 16, 16, 16, 16);
            DateTime             now             = DateTime.Now;
            string     fileName = "D:\\reportOrder_" + now.ToString("yyyyMMddHHmmss") + ".pdf";
            FileStream fs       = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
            PdfWriter  writer   = PdfWriter.GetInstance(doc, fs);

            doc.Open();
            float ySubPage      = 210;
            int   j             = 0;
            int   numberOfOrder = List_Num_Order;

            foreach (ProductsModel p in lsProductReport)
            {//4 pices per page
                numberOfOrder++;
                if (j == 0)
                {
                    doc.NewPage();                              //New Page
                }
                float          w         = doc.PageSize.Width;  //595
                float          h         = doc.PageSize.Height; //842
                PdfContentByte cb        = writer.DirectContent;
                float          xTextHead = 20;
                float          yTextHead = h - 20 - (ySubPage * j);
                cb.BeginText();
                cb.SetFontAndSize(GetTahoma().BaseFont, 9f); //Set the font information
                cb.MoveText(20, yTextHead);                  //Position the cursor for drawing
                string docCode           = "" + numberOfOrder.ToString().PadLeft(4, '0');
                string createDateTimeDoc = now.ToString("dd/MM/yyyy") + "   " + now.ToString("HH:mm") + " น.";
                cb.ShowText(docCode + "  ใบสั่งงานย่อย/ใบสั่งงาน  " + createDateTimeDoc); //Write some text
                cb.EndText();

                #region box1
                float xBox1 = 260;
                float yBox1 = h - 25 - (ySubPage * j);
                float wBox1 = 80;
                float hBox1 = 20;

                cb.BeginText();
                cb.SetFontAndSize(GetTahoma().BaseFont, 9f);
                cb.MoveText(xBox1 + 3, yBox1 + 5);
                cb.ShowText("ผู้อนุมัติ");
                cb.EndText();


                cb.Rectangle(xBox1, yBox1, wBox1, hBox1);//X,Y,W,H
                cb.Stroke();
                float xLine1 = xBox1 + 35;
                float yLine1 = h - 5 - (ySubPage * j);
                cb.MoveTo(xLine1, yBox1);
                cb.LineTo(xLine1, yLine1);
                cb.Stroke();
                #endregion

                #region box2
                float xBox2 = xBox1 + wBox1 + 5;
                float yBox2 = yBox1;
                float wbox2 = 130;
                float hBox2 = hBox1;

                cb.BeginText();
                cb.MoveText(xBox2 + 3, yBox2 + 5);
                cb.ShowText("ผู้ตรวจสอบ");
                cb.EndText();

                cb.Rectangle(xBox2, yBox2, wbox2, hBox2);//X,Y,W,H
                cb.Stroke();

                float xLine2 = xBox2 + 45;
                float yLine2 = yLine1;
                cb.MoveTo(xLine2, yBox2);
                cb.LineTo(xLine2, yLine2);
                cb.Stroke();

                cb.BeginText();
                cb.MoveText(xBox2 + 3, yBox2 + 5);
                cb.ShowText("ผู้ตรวจสอบ");
                cb.EndText();

                cb.BeginText();
                cb.MoveText(xBox2 + 100, yBox2 + 5);
                cb.ShowText("สโตร์");
                cb.EndText();
                cb.MoveTo(xLine2 + 50, yBox2);
                cb.LineTo(xLine2 + 50, yLine2);
                cb.Stroke();
                #endregion

                #region Box3
                float xBox3 = xBox2 + wbox2 + 5;
                float yBox3 = yBox1;
                float wbox3 = wBox1 + 20;
                float hBox3 = hBox1;

                cb.BeginText();
                cb.MoveText(xBox3 + 3, yBox3 + 5);
                cb.ShowText("ผู้เตรียม");
                cb.EndText();

                cb.Rectangle(xBox3, yBox3, wbox3, hBox3);//X,Y,W,H
                cb.Stroke();

                float xLine3 = xBox3 + 40;
                float yLine3 = yLine1;
                cb.MoveTo(xLine3, yBox3);
                cb.LineTo(xLine3, yLine3);
                cb.Stroke();
                #endregion

                #region Line2
                float xBox_OrderTo = xTextHead;
                float yBox_OrderTo = yBox3 - 17;
                float wBox_OrderTo = 130;
                float hBox_OrderTo = 15;

                cb.BeginText();
                cb.MoveText(xBox_OrderTo + 3, yBox_OrderTo + 5);
                cb.ShowText("ถึง :คุณ " + p.Order_to);
                cb.EndText();

                cb.Rectangle(xBox_OrderTo, yBox_OrderTo, wBox_OrderTo, hBox_OrderTo);//X,Y,W,H
                cb.Stroke();



                float xBox_Topic = xBox_OrderTo + 150;
                float yBox_Topic = yBox_OrderTo;
                float wBox_Topic = 145;
                float hBox_Topic = hBox_OrderTo;
                cb.BeginText();
                cb.MoveText(xBox_Topic, yBox_OrderTo + 5);
                cb.ShowText("เรื่อง : " + p.Vendor);
                cb.EndText();

                cb.Rectangle(xBox_Topic + 25, yBox_Topic, wBox_Topic, hBox_Topic);//X,Y,W,H
                cb.Stroke();

                float xBox_Order = xBox_Topic + 180;
                float yBox_Order = yBox_Topic;
                float wBox_Order = 130;
                float hBox_Order = hBox_Topic;
                cb.BeginText();
                cb.SetFontAndSize(GetTahoma().BaseFont, 7f);
                cb.MoveText(xBox_Order, yBox_Order + 5);
                cb.ShowText("จำนวนสั่งทำ/ซื้อ          " + p.Suggest_Order + "   " + p.PUnit_Name);
                cb.EndText();
                cb.Rectangle(xBox_Order - 5, yBox_Order, wBox_Order, hBox_Order);//X,Y,W,H
                cb.Stroke();

                float xBox_Min = xBox3 + 5;
                float yBox_Min = yBox_Order;
                float wBox_Min = 100;
                float hBox_Min = hBox_Order;

                cb.BeginText();
                cb.SetFontAndSize(GetTahoma().BaseFont, 9f);
                cb.MoveText(xBox_Min, yBox_Min + 5);
                cb.ShowText("min     " + p.Min_Stock + "   " + p.SUnit_Name);
                cb.EndText();
                cb.Rectangle(xBox_Min - 5, yBox_Min, wBox_Min, hBox_Min);//X,Y,W,H
                cb.Stroke();
                #endregion
                #region Line3
                float xLine_productName = xTextHead;
                float yLine_ProductName = yBox_OrderTo - 13;

                cb.BeginText();
                cb.SetFontAndSize(GetTahoma().BaseFont, 9f);
                cb.MoveText(xLine_productName, yLine_ProductName);
                cb.ShowText(p.Product_Code + " : " + p.Product_Name);
                cb.EndText();

                //float yLine_productUnder =
                cb.MoveTo(xLine_productName + 2, yLine_ProductName - 3);
                cb.LineTo(575, yLine_ProductName - 3);
                cb.Stroke();
                #endregion
                #region Line4
                float xLine_use = xLine_productName;
                float yline_use = yLine_ProductName - 15;

                cb.BeginText();
                cb.MoveText(xLine_use, yline_use);
                cb.ShowText("use : " + p.Use);
                cb.EndText();

                cb.MoveTo(xLine_use, yline_use - 3);
                cb.LineTo(575, yline_use - 3);
                cb.Stroke();

                #endregion
                #region line5
                float xbox5       = xLine_use;
                float ybox5       = yline_use - 23;
                float wBox5       = 67;
                float hBox5       = 20;
                float yTextInBox5 = ybox5 + 11;
                cb.Rectangle(xbox5, ybox5, wBox5, hBox5);//X,Y,W,H
                cb.Stroke();

                cb.BeginText();
                cb.SetFontAndSize(GetTahoma().BaseFont, 8f);
                cb.MoveText(xbox5 + 2, yTextInBox5);
                cb.ShowText("หัวหน้าแผนก หรือ");
                cb.EndText();
                cb.BeginText();
                cb.MoveText(xbox5 + 2, yTextInBox5 - 8);
                cb.ShowText("ผจก. ฝ่ายนั้นๆ เซ็น   ...........................  ว/ด/ป ................. จำนวนส่งงานเข้า ........................ ผู้ส่ง .................. ว/ด/ป ..................");
                cb.EndText();
                #endregion
                #region Lin6,7,8
                float xLine6    = xbox5;
                float yLin6     = ybox5 - 15;
                float xEndLine6 = 473;
                cb.MoveTo(xLine6, yLin6);
                cb.LineTo(xEndLine6, yLin6);
                cb.Stroke();
                float yLine7 = yLin6 - 15;
                cb.MoveTo(xLine6, yLine7);
                cb.LineTo(xEndLine6, yLine7);
                cb.Stroke();
                float yLine8 = yLine7 - 15;
                cb.MoveTo(xLine6, yLine8);
                cb.LineTo(xEndLine6, yLine8);
                cb.Stroke();
                #endregion
                #region lin9
                float xline9_sign = 150;
                float yLine9_sign = yLine8 - 20;
                cb.BeginText();
                cb.SetFontAndSize(GetTahoma().BaseFont, 9f);
                cb.MoveText(xline9_sign, yLine9_sign);
                cb.ShowText("รับสำเนาแล้ว  ลงชื่อ __________________ (                       ) วันที่ ____________");
                cb.EndText();
                #endregion
                #region box QTY
                float xBoxQty = 480;
                float yBoxQty = ybox5 - 70;
                float wBoxQty = 100;
                float hBoxQty = 90;
                cb.Rectangle(xBoxQty, yBoxQty, wBoxQty, hBoxQty);
                cb.Stroke();

                float xLineBoxQty = xBoxQty + 40;
                cb.MoveTo(xLineBoxQty, yBoxQty);//Vertical
                cb.LineTo(xLineBoxQty, yBoxQty + hBoxQty);
                cb.Stroke();

                float yLineHoBoxQty = yBoxQty + 55;
                cb.MoveTo(xBoxQty, yLineHoBoxQty);//Hori
                cb.LineTo(580, yLineHoBoxQty);
                cb.Stroke();

                float yTextRemainLP = yLineHoBoxQty + 25;
                cb.BeginText();
                cb.MoveText(xBoxQty + 2, yTextRemainLP);
                cb.ShowText("เหลือ LP       " + p.LP_QTY + "   " + p.SUnit_Name);
                cb.EndText();
                cb.BeginText();
                cb.MoveText(xBoxQty + 2, yTextRemainLP - 18);
                cb.ShowText("ที่ตั้ง LP");
                cb.EndText();


                cb.MoveTo(xBoxQty, yLineHoBoxQty - 30);//Hori
                cb.LineTo(580, yLineHoBoxQty - 30);
                cb.Stroke();

                float yTextRemainTD = yTextRemainLP - 18 - 18;
                cb.BeginText();
                cb.MoveText(xBoxQty + 2, yTextRemainTD);
                cb.ShowText("เหลือ TD     " + p.TD_QTY + "   " + p.SUnit_Name);
                cb.EndText();
                cb.BeginText();
                cb.MoveText(xBoxQty + 2, yTextRemainTD - 15);
                cb.ShowText("ที่ตั้ง TD");
                cb.EndText();

                float yTextTotalQty = yTextRemainTD - 15;
                cb.BeginText();
                cb.MoveText(xBoxQty + 2, yTextTotalQty - 18);
                cb.ShowText("เหลือรวม     " + p.TOTAL_QTY + "   " + p.SUnit_Name);
                cb.EndText();

                #endregion
                j++;
                if (j == 4)
                {
                    j = 0;
                }
            }
            doc.Close();
        }
Beispiel #16
0
        /**
        * Initializes a page.
        * <P>
        * If the footer/header is set, it is printed.
        * @throws DocumentException on error
        */
        protected internal void InitPage()
        {
            // the pagenumber is incremented
            pageN++;

            // initialisation of some page objects
            annotationsImp.ResetAnnotations();
            pageResources = new PageResources();

            writer.ResetContent();
            graphics = new PdfContentByte(writer);
            text = new PdfContentByte(writer);
            text.Reset();
            text.BeginText();
            textEmptySize = text.Size;

            markPoint = 0;
            SetNewPageSizeAndMargins();
            imageEnd = -1;
            indentation.imageIndentRight = 0;
            indentation.imageIndentLeft = 0;
            indentation.indentBottom = 0;
            indentation.indentTop = 0;
            currentHeight = 0;

            // backgroundcolors, etc...
            thisBoxSize = new Hashtable(boxSize);
            if (pageSize.BackgroundColor != null
            || pageSize.HasBorders()
            || pageSize.BorderColor != null) {
                Add(pageSize);
            }

            float oldleading = leading;
            int oldAlignment = alignment;
            // if there is a footer, the footer is added
            DoFooter();
            // we move to the left/top position of the page
            text.MoveText(Left, Top);
            DoHeader();
            pageEmpty = true;
            // if there is an image waiting to be drawn, draw it
            if (imageWait != null) {
                Add(imageWait);
                imageWait = null;
            }
            leading = oldleading;
            alignment = oldAlignment;
            CarriageReturn();

            IPdfPageEvent pageEvent = writer.PageEvent;
            if (pageEvent != null) {
                if (firstPageEvent) {
                    pageEvent.OnOpenDocument(writer, this);
                }
                pageEvent.OnStartPage(writer, this);
            }
            firstPageEvent = false;
        }
        protected void btnEnviar_Click(object sender, EventArgs e)
        {
            try
            {
                string     direccion_logo = "Av. Santa Rosa 4470, San Joaquin, Santiago - Tel: +56225526276";
                TipoMoneda moneda         = new TipoMoneda();
                Usuario    creador        = new Usuario();
                moneda.ID = Convert.ToInt32(Request.Form.Get(txtMoneda.UniqueID));
                moneda.Read();
                Encabezado encabezado    = (Encabezado)Session["encabezado"];
                string     correo        = Request.Form.Get(txtCorreo.UniqueID);
                string     rut           = Request.Form.Get(txtRut.UniqueID);
                string     razon         = Request.Form.Get(txtNombre.UniqueID);
                string     contacto      = Request.Form.Get(txtContacto.UniqueID);
                string     condicionpago = Request.Form.Get(txtCondicionesPago.UniqueID);
                string     entrega       = Request.Form.Get(txtEntrega.UniqueID);
                string     direccion     = Request.Form.Get(txtDireccion.UniqueID);
                string     fecha         = Request.Form.Get(txtFecha_.UniqueID);
                string     neto          = Request.Form.Get(txtNeto.UniqueID);
                string     telefono      = Request.Form.Get(txtTelefono.UniqueID);
                string     total         = Request.Form.Get(txtTotal.UniqueID);
                Detalle    detalle       = new Detalle();
                detalle.Correlativo           = encabezado.Correlativo;
                encabezado.CondicionPago      = condicionpago;
                encabezado.Contacto           = contacto;
                encabezado.Correo             = correo;
                encabezado.Entrega            = entrega;
                encabezado.Direccion          = direccion;
                encabezado.Estado             = "Pendiente";
                encabezado.Observacion_estado = " ";
                //encabezado.Fecha = fecha.ToString("dd/MM/yyyy");
                encabezado.Fecha = fecha;
                //encabezado.Iva = Convert.ToInt32(txtIVA.Value);
                encabezado.Tipo_moneda  = moneda.Nombre;
                encabezado.Iva          = 0;
                encabezado.Neto         = Convert.ToDouble(neto.ToString().Replace(".", ","));
                encabezado.Razon_social = razon;
                encabezado.Rut          = rut;
                encabezado.Telefono     = telefono;
                encabezado.Total        = Convert.ToDouble(total.ToString().Replace(".", ","));
                creador.Usuario_        = encabezado.Codigo_usuario;
                creador.Read();
                if (encabezado.Update())
                {
                    detalle.LimpiarDetalleCorrelativo();
                    List <string> lista       = ListValues();
                    string        correlativo = encabezado.Correlativo.ToString();
                    CreacionDetalle(correlativo, lista);
                    byte[] bytesarray = null;
                    using (var ms = new MemoryStream())
                    {
                        using (var document = new Document(PageSize.A4, 20f, 20f, 45f, 35f)) //PageSize.A4, 20f, 20f, 65f, 35f--PageSize.A4, 20f, 20f, 75f, 35f
                        {
                            using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
                            {
                                document.Open();
                                PdfContentByte canvas = writer.DirectContent;
                                writer.CompressionLevel = 0;
                                canvas.SaveState();
                                canvas.BeginText();
                                canvas.MoveText(118, 773);
                                canvas.SetFontAndSize(BaseFont.CreateFont(), 8);
                                canvas.ShowText(direccion_logo);
                                canvas.EndText();
                                canvas.RestoreState();
                                using (var strreader = new StringReader(HTMLPage(ListValues(), encabezado, correlativo, creador, moneda).ToString()))
                                {
                                    var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/pdf/logo.png"));
                                    logo.ScaleAbsoluteWidth(450);
                                    logo.ScaleAbsoluteHeight(100);
                                    logo.SetAbsolutePosition(0, 750);
                                    document.Add(logo);
                                    //set factories
                                    HtmlPipelineContext htmlcontext = new HtmlPipelineContext(null);
                                    htmlcontext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                                    //set css
                                    ICSSResolver cssresolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                                    cssresolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/pdf/estilo.css"), true);
                                    //export
                                    IPipeline pipeline = new CssResolverPipeline(cssresolver, new HtmlPipeline(htmlcontext, new PdfWriterPipeline(document, writer)));
                                    var       worker   = new XMLWorker(pipeline, true);
                                    var       xmlparse = new XMLParser(true, worker);
                                    //var xmlparse = new XMLParser();
                                    xmlparse.Parse(strreader);
                                    xmlparse.Flush();
                                }
                                document.Close();
                            }
                        }
                        bytesarray = ms.ToArray();
                        ms.Close();
                        // clears all content output from the buffer stream
                        Response.Clear();
                        // gets or sets the http mime type of the output stream.
                        Response.ContentType = "application/pdf";
                        // adds an http header to the output stream
                        Response.AddHeader("content-disposition", "attachment; filename=cotizacion_" + correlativo + ".pdf");

                        //gets or sets a value indicating whether to buffer output and send it after
                        // the complete response is finished processing.
                        Response.Buffer = true;
                        // sets the cache-control header to one of the values of system.web.httpcacheability.
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        // writes a string of binary characters to the http output stream. it write the generated bytes .
                        Response.BinaryWrite(bytesarray);
                        // sends all currently buffered output to the client, stops execution of the
                        // page, and raises the system.web.httpapplication.endrequest event.

                        Response.Flush();                                          // sends all currently buffered output to the client.
                        Response.SuppressContent = true;                           // gets or sets a value indicating whether to send http content to the client.
                        HttpContext.Current.ApplicationInstance.CompleteRequest(); // causes asp.net to bypass all events and filtering in the http pipeline chain of execution and directly execute the endrequest event.
                                                                                   // closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
                        Response.Close();
                    }
                    Session["encabezado"] = null;
                    Session["detalle"]    = null;
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Cotizacion modificada" + "');", true);
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
            }
        }
        protected void gvCotizacion_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            Usuario    usuario        = (Usuario)Session["usuario"];
            TipoMoneda moneda         = new TipoMoneda();
            string     direccion_logo = "Av. Santa Rosa 4470, San Joaquin, Santiago - Tel: +56225526276";

            switch (e.CommandName)
            {
            case "Select":
                int              index       = Convert.ToInt32(e.CommandArgument);
                GridViewRow      selectedRow = gvCotizacion.Rows[index];
                TableCell        corr_id     = selectedRow.Cells[0];
                string           correlativo = corr_id.Text;
                Encabezado       encabezado  = new Encabezado();
                Usuario          creador     = new Usuario();
                ColeccionDetalle detalles    = new ColeccionDetalle();
                encabezado.Correlativo = Convert.ToInt32(correlativo);
                encabezado.Read();
                moneda.Nombre = encabezado.Tipo_moneda;
                moneda.ReadNombre();
                creador.Usuario_ = encabezado.Codigo_usuario;
                creador.Read();
                List <Detalle> list = detalles.ListaDetalle(correlativo);
                try
                {
                    byte[] bytesarray = null;
                    using (var ms = new MemoryStream())
                    {
                        using (var document = new Document(PageSize.A4, 20f, 20f, 45f, 35f))     //PageSize.A4, 20f, 20f, 65f, 35f--PageSize.A4, 20f, 20f, 75f, 35f
                        {
                            using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
                            {
                                document.Open();
                                PdfContentByte canvas = writer.DirectContent;
                                writer.CompressionLevel = 0;
                                canvas.SaveState();
                                canvas.BeginText();
                                canvas.MoveText(118, 773);
                                canvas.SetFontAndSize(BaseFont.CreateFont(), 8);
                                canvas.ShowText(direccion_logo);
                                canvas.EndText();
                                canvas.RestoreState();
                                using (var strreader = new StringReader(HTMLPage(list, encabezado, correlativo, creador, moneda).ToString()))
                                {
                                    var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/pdf/logo.png"));
                                    logo.ScaleAbsoluteWidth(450);
                                    logo.ScaleAbsoluteHeight(100);
                                    logo.SetAbsolutePosition(0, 750);
                                    document.Add(logo);
                                    //set factories
                                    HtmlPipelineContext htmlcontext = new HtmlPipelineContext(null);
                                    htmlcontext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                                    //set css
                                    ICSSResolver cssresolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                                    cssresolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/pdf/estilo.css"), true);
                                    //export
                                    IPipeline pipeline = new CssResolverPipeline(cssresolver, new HtmlPipeline(htmlcontext, new PdfWriterPipeline(document, writer)));
                                    var       worker   = new XMLWorker(pipeline, true);
                                    var       xmlparse = new XMLParser(true, worker);
                                    xmlparse.Parse(strreader);
                                    xmlparse.Flush();
                                }
                                document.Close();
                            }
                        }
                        bytesarray = ms.ToArray();
                        ms.Close();
                        Response.Clear();
                        Response.ContentType = "application/pdf";
                        Response.AddHeader("content-disposition", "attachment; filename=cotizacion_" + correlativo + "_reimpresion.pdf");
                        Response.Buffer = true;
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        Response.BinaryWrite(bytesarray);
                        Response.Flush();
                        Response.SuppressContent = true;
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        Response.Close();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
                    break;
                }
            //case "Edit":
            //    try
            //    {
            //        int index2 = Convert.ToInt32(e.CommandArgument);
            //        GridViewRow selectedRow2 = gvCotizacion.Rows[index2];
            //        TableCell correlativo_id = selectedRow2.Cells[0];
            //        //TableCell razon_social = selectedRow2.Cells[1];
            //        //TableCell rut = selectedRow2.Cells[2];
            //        //TableCell contacto = selectedRow2.Cells[3];
            //        //TableCell fecha = selectedRow2.Cells[4];
            //        TableCell telefono = selectedRow2.Cells[5];
            //        TableCell correo = selectedRow2.Cells[6];
            //        //TableCell condicion_pago = selectedRow2.Cells[7];
            //        //TableCell entrega = selectedRow2.Cells[8];
            //        //TableCell direccion = selectedRow2.Cells[9];
            //        //TableCell tipo_moneda = selectedRow2.Cells[10];
            //        TableCell estado = selectedRow2.Cells[11];
            //        //TableCell codigo_usuario = selectedRow2.Cells[12];
            //        //TableCell neto = selectedRow2.Cells[13];
            //        //TableCell iva = selectedRow2.Cells[14];
            //        //TableCell total = selectedRow2.Cells[15];
            //        Encabezado encabezado2 = new Encabezado();
            //        encabezado2.Correlativo = Convert.ToInt32(correlativo_id.Text);
            //        encabezado2.Read();
            //        encabezado2.Telefono = telefono.Text;
            //        encabezado2.Correo = correo.Text;
            //        encabezado2.Estado = estado.Text;
            //        encabezado2.Update();
            //        break;
            //    }
            //    catch (Exception ex)
            //    {
            //        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
            //        break;
            //    }

            //case "Delete":
            //    int index2 = Convert.ToInt32(e.CommandArgument);
            //    GridViewRow selectedRow2 = gvCotizacion.Rows[index2];
            //    TableCell corr_id2 = selectedRow2.Cells[0];
            //    string correlativo2 = corr_id2.Text;
            //    Encabezado encabezado2 = new Encabezado();
            //    encabezado2.Correlativo = Convert.ToInt32(correlativo2);
            //    encabezado2.Delete();
            //   break;
            case "Details":
                int         index3       = Convert.ToInt32(e.CommandArgument);
                GridViewRow selectedRow3 = gvCotizacion.Rows[index3];
                TableCell   corr_id2     = selectedRow3.Cells[0];
                string      correlativo2 = corr_id2.Text;
                Session["cotizacion"] = correlativo2;
                Response.Redirect("../Cotizacion/RevisionDetalles.aspx", false);
                Context.ApplicationInstance.CompleteRequest();
                break;

            case "Excel":
                int              index4       = Convert.ToInt32(e.CommandArgument);
                GridViewRow      selectedRow4 = gvCotizacion.Rows[index4];
                TableCell        corr_id3     = selectedRow4.Cells[0];
                string           correlativo3 = corr_id3.Text;
                Encabezado       encabezado3  = new Encabezado();
                Usuario          creador2     = new Usuario();
                ColeccionDetalle detalles2    = new ColeccionDetalle();
                encabezado3.Correlativo = Convert.ToInt32(correlativo3);
                encabezado3.Read();
                moneda.Nombre = encabezado3.Tipo_moneda;
                moneda.ReadNombre();
                creador2.Usuario_ = encabezado3.Codigo_usuario;
                creador2.Read();
                List <Detalle> list2 = detalles2.ListaDetalle(correlativo3);
                try
                {
                    XLWorkbook workbook = DocumentoExcel(list2, encabezado3, correlativo3, creador2, moneda);
                    // Prepare the response
                    Response.Clear();
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;filename=\"cotizacion_excel_" + correlativo3 + ".xlsx\"");
                    //Response.AddHeader("content-disposition", "attachment;filename=cotizacion_excel_" + correlativo3 + ".xlsx");
                    //byte[] bytesarray = null;
                    // Flush the workbook to the Response.OutputStream
                    using (var memoryStream = new MemoryStream())
                    {
                        workbook.SaveAs(memoryStream);
                        memoryStream.WriteTo(Response.OutputStream);
                        memoryStream.Close();

                        //bytesarray = memoryStream.ToArray();
                        //Response.End();
                        Response.Buffer = true;
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        //Response.BinaryWrite(bytesarray);
                        Response.Flush();
                        Response.SuppressContent = true;
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        Response.Close();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
                    break;
                }

            case "Cotizacion":
                int         index5       = Convert.ToInt32(e.CommandArgument);
                GridViewRow selectedRow5 = gvCotizacion.Rows[index5];
                TableCell   corr_id4     = selectedRow5.Cells[0];
                string      correlativo4 = corr_id4.Text;
                try
                {
                    Encabezado       encabezado4 = new Encabezado();
                    ColeccionDetalle detalles3   = new ColeccionDetalle();
                    encabezado4.Correlativo = Convert.ToInt32(correlativo4);
                    encabezado4.Read();
                    List <Detalle> list3 = detalles3.ListaDetalle(correlativo4);

                    Session["encabezado"] = encabezado4;
                    Session["detalle"]    = list3;
                    Response.Redirect("../Cotizacion/EditorCotizacion.aspx", false);
                    Context.ApplicationInstance.CompleteRequest();
                    break;
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
                    break;
                }

            default:
                break;
            }
        }
Beispiel #19
0
// ===========================================================================
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                writer.SetTagged();
                // step 3
                document.Open();
                // step 4
                PdfContentByte cb = writer.DirectContent;
                BaseFont       bf = BaseFont.CreateFont(
                    BaseFont.HELVETICA,
                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED
                    );
                BaseFont bf2 = BaseFont.CreateFont(
                    "c:/windows/fonts/msgothic.ttc,1",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED
                    );

                PdfStructureTreeRoot root = writer.StructureTreeRoot;
                PdfStructureElement  div  = new PdfStructureElement(
                    root, new PdfName("Div")
                    );
                PdfDictionary dict;

                cb.BeginMarkedContentSequence(div);

                cb.BeginText();
                cb.MoveText(36, 788);
                cb.SetFontAndSize(bf, 12);
                cb.SetLeading(18);
                cb.ShowText("These are some famous movies by Stanley Kubrick: ");
                dict = new PdfDictionary();
                dict.Put(PdfName.E, new PdfString("Doctor"));
                cb.BeginMarkedContentSequence(new PdfName("Span"), dict, true);
                cb.NewlineShowText("Dr.");
                cb.EndMarkedContentSequence();
                cb.ShowText(
                    " Strangelove or: How I Learned to Stop Worrying and Love the Bomb."
                    );
                dict = new PdfDictionary();
                dict.Put(PdfName.E, new PdfString("Eyes Wide Shut."));
                cb.BeginMarkedContentSequence(new PdfName("Span"), dict, true);
                cb.NewlineShowText("EWS");
                cb.EndMarkedContentSequence();
                cb.EndText();
                dict = new PdfDictionary();
                dict.Put(PdfName.LANG, new PdfString("en-us"));
                dict.Put(new PdfName("Alt"), new PdfString("2001: A Space Odyssey."));
                cb.BeginMarkedContentSequence(new PdfName("Span"), dict, true);
                Image img = Image.GetInstance(Path.Combine(
                                                  Utility.ResourcePosters, "0062622.jpg"
                                                  ));
                img.ScaleToFit(1000, 100);
                img.SetAbsolutePosition(36, 640);
                cb.AddImage(img);
                cb.EndMarkedContentSequence();

                cb.BeginText();
                cb.MoveText(36, 620);
                cb.SetFontAndSize(bf, 12);
                cb.ShowText("This is a movie by Akira Kurosawa: ");
                dict = new PdfDictionary();
                dict.Put(PdfName.ACTUALTEXT, new PdfString("Seven Samurai."));
                cb.BeginMarkedContentSequence(new PdfName("Span"), dict, true);
                cb.SetFontAndSize(bf2, 12);
                cb.ShowText("\u4e03\u4eba\u306e\u4f8d");
                cb.EndMarkedContentSequence();
                cb.EndText();

                cb.EndMarkedContentSequence();
            }
        }