Example #1
1
        // From <ClickButt> -> PdfConnector PdfCreatora <- PdfCreator(naemBank,Bodytext)
        // Form <Image> <- PdfConnector -- tworzyć pdf |
        public Form1() 
        {
            while (!fileBanksLists.EndOfStream)
            {
                    InitializeComponent();
            
                     using (FileStream file = new FileStream(String.Format(path, nameBank), FileMode.Create))
                    {

                        Document document = new Document(PageSize.A7);
                        PdfWriter writer = PdfWriter.GetInstance(document, file);
              
                        /// Create metadate pdf file
                        document.AddAuthor(nameBank);
                        document.AddLanguage("pl");
                        document.AddSubject("Payment transaction");
                        document.AddTitle("Transaction");
                        document.AddKeywords("OutcomingNumber :" + OutcomingNumber);
                        document.AddKeywords("IncomingNumber :" + IncomingNumber);
                        /// Create text in pdf file
                        document.Open();
                        document.Add(new Paragraph(_przelew + "\n"));
                        document.Add(new Paragraph(String.Format("Bank {0}: zaprasza\n", nameBank)));
                        document.Add(new Paragraph(DateTime.Now.ToString()));
                        document.Close();
                        writer.Close();
                        file.Close();
                    }
            }
            
            
        }
 public override void SetUp()
 {
     base.SetUp();
     INDEX_SIZE = AtLeast(2000);
     Index = NewDirectory();
     RandomIndexWriter writer = new RandomIndexWriter(Random(), Index);
     RandomGen random = new RandomGen(this, Random());
     for (int i = 0; i < INDEX_SIZE; ++i) // don't decrease; if to low the
     {
         // problem doesn't show up
         Document doc = new Document();
         if ((i % 5) != 0) // some documents must not have an entry in the first
         {
             // sort field
             doc.Add(NewStringField("publicationDate_", random.LuceneDate, Field.Store.YES));
         }
         if ((i % 7) == 0) // some documents to match the query (see below)
         {
             doc.Add(NewTextField("content", "test", Field.Store.YES));
         }
         // every document has a defined 'mandant' field
         doc.Add(NewStringField("mandant", Convert.ToString(i % 3), Field.Store.YES));
         writer.AddDocument(doc);
     }
     Reader = writer.Reader;
     writer.Dispose();
     Query = new TermQuery(new Term("content", "test"));
 }
        public override void SetUp()
        {
            base.SetUp();
            Document doc;
            Rd1 = NewDirectory();
            IndexWriter iw1 = new IndexWriter(Rd1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));

            doc = new Document();
            doc.Add(NewTextField("field1", "the quick brown fox jumps", Field.Store.YES));
            doc.Add(NewTextField("field2", "the quick brown fox jumps", Field.Store.YES));
            iw1.AddDocument(doc);

            iw1.Dispose();
            Rd2 = NewDirectory();
            IndexWriter iw2 = new IndexWriter(Rd2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));

            doc = new Document();
            doc.Add(NewTextField("field1", "the fox jumps over the lazy dog", Field.Store.YES));
            doc.Add(NewTextField("field3", "the fox jumps over the lazy dog", Field.Store.YES));
            iw2.AddDocument(doc);

            iw2.Dispose();

            this.Ir1 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(Rd1));
            this.Ir2 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(Rd2));
        }
Example #4
0
        public override Document Import()
        {
            var toret = new Document();
            Question q = null;
            string line;

            toret.Clear();
            line = this.ReadLine();
            while ( line != null ) {
                line = line.Trim();

                if ( line.Length > 0 ) {
                    if ( IsQuestion( ref line ) ) {
                        if ( q != null ) {
                            toret.Add( q );
                        }

                        q = new Question( line );
                        q.ClearAnswers();
                    }
                    else
                    if ( IsAnswer( ref line ) ) {
                        q.AddAnswer( line );
                    }
                }

                line = this.ReadLine();
            }

            if ( q != null ) {
                toret.Add( q );
            }

            return toret;
        }
Example #5
0
        public static void UploadDocuments(SearchIndexClient indexClient, string fileId, string fileName, string ocrText, KeyPhraseResult keyPhraseResult)
        {
            List<IndexAction> indexOperations = new List<IndexAction>();
            var doc = new Document();
            doc.Add("fileId", fileId);
            doc.Add("fileName", fileName);
            doc.Add("ocrText", ocrText);
            doc.Add("keyPhrases", keyPhraseResult.KeyPhrases.ToList());
            indexOperations.Add(IndexAction.Upload(doc));

            try
            {
                indexClient.Documents.Index(new IndexBatch(indexOperations));
            }
            catch (IndexBatchException e)
            {
                // Sometimes when your Search service is under load, indexing will fail for some of the documents in
                // the batch. Depending on your application, you can take compensating actions like delaying and
                // retrying. For this simple demo, we just log the failed document keys and continue.
                Console.WriteLine(
                "Failed to index some of the documents: {0}",
                       String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));
            }

        }
Example #6
0
        public bool buildPoiIndex(String sdbName,String indexPath)
        {
            soDataSource ds = axSuperWorkspace1.OpenDataSource(sdbName, "", seEngineType.sceSDBPlus, true);
            if (ds.Datasets.Count == 0)
            {
                return false;
            }

            soDataset dataset = ds.Datasets[1];
            if (dataset == null)
            {
                return false;
            }

            soDatasetVector objDtv = (soDatasetVector)dataset;

            soRecordset objRd = objDtv.Query("", false, null, "");

            if (objRd == null)
            {
                return false;
            }

            int count = objRd.RecordCount;
            int i = 0;

            IndexWriter writer = new IndexWriter(indexPath, objCA, true);
            objRd.MoveFirst();
            while (!objRd.IsEOF())
            {

                Document doc = new Document();
                String name = objRd.GetFieldValueText("NAME_CHN");
                doc.Add(new Field("Name", name, Field.Store.YES, Field.Index.TOKENIZED));
                double x = (double)objRd.GetFieldValue("X_COORD");
                double y = (double)objRd.GetFieldValue("Y_COORD");
                List<Byte> locationByte = new List<Byte>();
                locationByte.AddRange(BitConverter.GetBytes(x));
                locationByte.AddRange(BitConverter.GetBytes(y));

                doc.Add(new Field("Location", locationByte.ToArray(), Field.Store.YES));
                writer.AddDocument(doc);

                objRd.MoveNext();
                i++;

                this.backgroundWorker1.ReportProgress(i*100 / count);
                //if (i== 100)
                //{
                //    break;
                //}
            }

            this.backgroundWorker1.ReportProgress(100);
            writer.Close();
            axSuperWorkspace1.Close();

            return true;
        }
Example #7
0
        private void CreateIndex(IndexWriter writer, string a, string b)
        {
            Document doc = new Document();
            doc.Add(new Field("title", a, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("content", b, Field.Store.YES, Field.Index.ANALYZED));

            writer.AddDocument(doc);
            writer.Commit();
        }
Example #8
0
        public virtual void TestPayloadFieldBit()
        {
            Directory ram = NewDirectory();
            PayloadAnalyzer analyzer = new PayloadAnalyzer();
            IndexWriter writer = new IndexWriter(ram, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
            Document d = new Document();
            // this field won't have any payloads
            d.Add(NewTextField("f1", "this field has no payloads", Field.Store.NO));
            // this field will have payloads in all docs, however not for all term positions,
            // so this field is used to check if the DocumentWriter correctly enables the payloads bit
            // even if only some term positions have payloads
            d.Add(NewTextField("f2", "this field has payloads in all docs", Field.Store.NO));
            d.Add(NewTextField("f2", "this field has payloads in all docs NO PAYLOAD", Field.Store.NO));
            // this field is used to verify if the SegmentMerger enables payloads for a field if it has payloads
            // enabled in only some documents
            d.Add(NewTextField("f3", "this field has payloads in some docs", Field.Store.NO));
            // only add payload data for field f2
            analyzer.SetPayloadData("f2", "somedata".GetBytes(IOUtils.CHARSET_UTF_8), 0, 1);
            writer.AddDocument(d);
            // flush
            writer.Dispose();

            SegmentReader reader = GetOnlySegmentReader(DirectoryReader.Open(ram));
            FieldInfos fi = reader.FieldInfos;
            Assert.IsFalse(fi.FieldInfo("f1").HasPayloads(), "Payload field bit should not be set.");
            Assert.IsTrue(fi.FieldInfo("f2").HasPayloads(), "Payload field bit should be set.");
            Assert.IsFalse(fi.FieldInfo("f3").HasPayloads(), "Payload field bit should not be set.");
            reader.Dispose();

            // now we add another document which has payloads for field f3 and verify if the SegmentMerger
            // enabled payloads for that field
            analyzer = new PayloadAnalyzer(); // Clear payload state for each field
            writer = new IndexWriter(ram, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode_e.CREATE));
            d = new Document();
            d.Add(NewTextField("f1", "this field has no payloads", Field.Store.NO));
            d.Add(NewTextField("f2", "this field has payloads in all docs", Field.Store.NO));
            d.Add(NewTextField("f2", "this field has payloads in all docs", Field.Store.NO));
            d.Add(NewTextField("f3", "this field has payloads in some docs", Field.Store.NO));
            // add payload data for field f2 and f3
            analyzer.SetPayloadData("f2", "somedata".GetBytes(IOUtils.CHARSET_UTF_8), 0, 1);
            analyzer.SetPayloadData("f3", "somedata".GetBytes(IOUtils.CHARSET_UTF_8), 0, 3);
            writer.AddDocument(d);

            // force merge
            writer.ForceMerge(1);
            // flush
            writer.Dispose();

            reader = GetOnlySegmentReader(DirectoryReader.Open(ram));
            fi = reader.FieldInfos;
            Assert.IsFalse(fi.FieldInfo("f1").HasPayloads(), "Payload field bit should not be set.");
            Assert.IsTrue(fi.FieldInfo("f2").HasPayloads(), "Payload field bit should be set.");
            Assert.IsTrue(fi.FieldInfo("f3").HasPayloads(), "Payload field bit should be set.");
            reader.Dispose();
            ram.Dispose();
        }
        private void btnFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dia = new FolderBrowserDialog();
            DialogResult res = dia.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            FSDirectory dir = FSDirectory.GetDirectory(Environment.CurrentDirectory + "\\LuceneIndex");
            //Lucene.Net.Store.RAMDirectory dir = new RAMDirectory();
            Lucene.Net.Analysis.Standard.StandardAnalyzer an = new Lucene.Net.Analysis.Standard.StandardAnalyzer();
            IndexWriter wr = new IndexWriter(dir, an,true);
            IStemmer stemmer = new EnglishStemmer();
            DirectoryInfo diMain = new DirectoryInfo(dia.SelectedPath);
            foreach(FileInfo fi in diMain.GetFiles()){
                Document doc = new Document();
                doc.Add(new Field("title", fi.Name,Field.Store.YES, Field.Index.NO));
                //doc.Add(new Field("text", File.ReadAllText(fi.FullName),Field.Store.YES, Field.Index.TOKENIZED,Field.TermVector.YES));
                doc.Add(new Field("text", PerformStemming(stemmer,NLPToolkit.Tokenizer.TokenizeNow(File.ReadAllText(fi.FullName)).ToArray()), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES));
                wr.AddDocument(doc);
            }
            wr.Optimize();
            wr.Flush();
            wr.Close();
            dir.Close();

            IndexReader reader = IndexReader.Open(dir);
            for (int i = 0; i < reader.MaxDoc(); i++)
            {
                if (reader.IsDeleted(i))
                    continue;

                Document doc = reader.Document(i);
                String docId = doc.Get("docId");
                foreach (TermFreqVector vector in reader.GetTermFreqVectors(i))
                {
                    foreach(string term in vector.GetTerms()){
                        Console.WriteLine(term);
                    }
                }
                // do something with docId here...
            }
            //IndexSearcher search = new IndexSearcher(wr.GetReader());

            //MoreLikeThis mlt = new MoreLikeThis(wr.GetReader());
            //FileInfo fitarget = new FileInfo(@"C:\Users\peacemaker\Desktop\TestNoBitcoin\test.txt");
            //Query query = mlt.Like(fitarget);

            //var hits = search.Search(query, int.MaxValue);
            //foreach (ScoreDoc doc in hits.ScoreDocs)
            //{
            //    textBox1.Text += doc.Score + Environment.NewLine;
            //}
        }
Example #10
0
        public virtual void TestBefore()
        {
            // create an index
            Directory indexStore = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(Random(), indexStore);

            long now = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

            Document doc = new Document();
            // add time that is in the past
            doc.Add(NewStringField("datefield", DateTools.TimeToString(now - 1000, DateTools.Resolution.MILLISECOND), Field.Store.YES));
            doc.Add(NewTextField("body", "Today is a very sunny day in New York City", Field.Store.YES));
            writer.AddDocument(doc);

            IndexReader reader = writer.Reader;
            writer.Dispose();
            IndexSearcher searcher = NewSearcher(reader);

            // filter that should preserve matches
            // DateFilter df1 = DateFilter.Before("datefield", now);
            TermRangeFilter df1 = TermRangeFilter.NewStringRange("datefield", DateTools.TimeToString(now - 2000, DateTools.Resolution.MILLISECOND), DateTools.TimeToString(now, DateTools.Resolution.MILLISECOND), false, true);
            // filter that should discard matches
            // DateFilter df2 = DateFilter.Before("datefield", now - 999999);
            TermRangeFilter df2 = TermRangeFilter.NewStringRange("datefield", DateTools.TimeToString(0, DateTools.Resolution.MILLISECOND), DateTools.TimeToString(now - 2000, DateTools.Resolution.MILLISECOND), true, false);

            // search something that doesn't exist with DateFilter
            Query query1 = new TermQuery(new Term("body", "NoMatchForthis"));

            // search for something that does exists
            Query query2 = new TermQuery(new Term("body", "sunny"));

            ScoreDoc[] result;

            // ensure that queries return expected results without DateFilter first
            result = searcher.Search(query1, null, 1000).ScoreDocs;
            Assert.AreEqual(0, result.Length);

            result = searcher.Search(query2, null, 1000).ScoreDocs;
            Assert.AreEqual(1, result.Length);

            // run queries with DateFilter
            result = searcher.Search(query1, df1, 1000).ScoreDocs;
            Assert.AreEqual(0, result.Length);

            result = searcher.Search(query1, df2, 1000).ScoreDocs;
            Assert.AreEqual(0, result.Length);

            result = searcher.Search(query2, df1, 1000).ScoreDocs;
            Assert.AreEqual(1, result.Length);

            result = searcher.Search(query2, df2, 1000).ScoreDocs;
            Assert.AreEqual(0, result.Length);
            reader.Dispose();
            indexStore.Dispose();
        }
Example #11
0
 private void button1_Click(object sender, EventArgs e)
 {
     Document PdfDoc = new Document();
     PdfWriter pdfwriter=PdfWriter.GetInstance(PdfDoc,new FileStream("sample.pdf",FileMode.Create));
     PdfDoc.Open();
     PdfDoc.Add(new Paragraph("anurag ambush"));
     PdfDoc.NewPage();
     PdfDoc.Add(new Paragraph("hello world again"));
     PdfDoc.Close();
     
     
 }
        public void TestCalculateSizeOfComplexDoc()
        {
            var doc = new Document();
            doc.Add("a", "a");
            doc.Add("b", 1);
            var sub = new Document().Add("c_1", 1).Add("c_2", DateTime.Now);
            doc.Add("c", sub);
            var ms = new MemoryStream();
            var writer = new BsonWriter(ms, new BsonDocumentDescriptor());

            Assert.AreEqual(51, writer.CalculateSizeObject(doc));
        }
Example #13
0
 private static Document generarEncabezado(Document doc, string nombreSimulacion, string fecha, string hora)
 {
     string path = Application.StartupPath + "\\Resources\\logo.png";
     Image logo = Image.GetInstance(new Uri(path));
     logo.ScalePercent(30);
     logo.Alignment = Image.TEXTWRAP | Image.ALIGN_LEFT;
     string encabezadoStr = string.Format("Simulador FFCC\nNombre de Simulación: {0}         Fecha: {1}      Hora: {2}", nombreSimulacion, fecha, hora);
     Paragraph encabezado = new Paragraph(encabezadoStr, FontFactory.GetFont("ARIAL", 10, iTextSharp.text.Font.BOLDITALIC));
     doc.Add(logo);
     doc.Add(encabezado);
     return doc;
 }
Example #14
0
        private void btnPrint_Click(object sender, EventArgs e)
        {
            // Create a Document object
            var document = new Document(PageSize.A4, 50, 50, 25, 25);

            string file = "Choo.pdf";
            // Create a new PdfWriter object, specifying the output stream
            var output = new MemoryStream();
            //var writer = PdfWriter.GetInstance(document, output);
            var writer = PdfWriter.GetInstance(document, new FileStream(file, FileMode.Create));

            // Open the Document for writing
            document.Open();

            var titleFont = FontFactory.GetFont("Arial", 18);
            var subTitleFont = FontFactory.GetFont("Arial", 14);
            var boldTableFont = FontFactory.GetFont("Arial", 12);
            var endingMessageFont = FontFactory.GetFont("Arial", 10);
            var bodyFont = FontFactory.GetFont("Arial", 12);

            //document.Add(new Paragraph("Northwind Traders Receipt", titleFont);
            Paragraph tit = new Paragraph();
            Chunk c1 = new Chunk("  Ingresos Diarios \n", titleFont);
            Chunk c2 = new Chunk("Ciclo Escolar 2012 - 2013 \n");
            Chunk c3 = new Chunk("Dia consultado : 25/01/2013");
            tit.Add(c1);
            tit.Add(c2);
            tit.Add(c3);
            tit.IndentationLeft = 200f;
            document.Add(tit);

            PdfContentByte cb = writer.DirectContent;
            cb.MoveTo(50, document.PageSize.Height / 2);
            cb.LineTo(document.PageSize.Width - 50, document.PageSize.Height / 2);
            cb.Stroke();

            var orderInfoTable = new PdfPTable(2);
            orderInfoTable.HorizontalAlignment = 0;
            orderInfoTable.SpacingBefore = 10;
            orderInfoTable.SpacingAfter = 10;
            orderInfoTable.DefaultCell.Border = 0;
            orderInfoTable.SetWidths(new int[] { 1, 4 });

            orderInfoTable.AddCell(new Phrase("Order:", boldTableFont));
            orderInfoTable.AddCell("textorder");
            orderInfoTable.AddCell(new Phrase("Price:", boldTableFont));
            orderInfoTable.AddCell(Convert.ToDecimal(444444).ToString("c"));

            document.Add(orderInfoTable);
            document.Close();
            System.Diagnostics.Process.Start(file);
        }
        public override void SetUp()
        {
            base.SetUp();
            Dir = NewDirectory();
            FieldName = Random().NextBoolean() ? "field" : ""; // sometimes use an empty string as field name
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.KEYWORD, false)).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000)));
            List<string> terms = new List<string>();
            int num = AtLeast(200);
            for (int i = 0; i < num; i++)
            {
                Document doc = new Document();
                doc.Add(NewStringField("id", Convert.ToString(i), Field.Store.NO));
                int numTerms = Random().Next(4);
                for (int j = 0; j < numTerms; j++)
                {
                    string s = TestUtil.RandomUnicodeString(Random());
                    doc.Add(NewStringField(FieldName, s, Field.Store.NO));
                    // if the default codec doesn't support sortedset, we will uninvert at search time
                    if (DefaultCodecSupportsSortedSet())
                    {
                        doc.Add(new SortedSetDocValuesField(FieldName, new BytesRef(s)));
                    }
                    terms.Add(s);
                }
                writer.AddDocument(doc);
            }

            if (VERBOSE)
            {
                // utf16 order
                terms.Sort();
                Console.WriteLine("UTF16 order:");
                foreach (string s in terms)
                {
                    Console.WriteLine("  " + UnicodeUtil.ToHexString(s));
                }
            }

            int numDeletions = Random().Next(num / 10);
            for (int i = 0; i < numDeletions; i++)
            {
                writer.DeleteDocuments(new Term("id", Convert.ToString(Random().Next(num))));
            }

            Reader = writer.Reader;
            Searcher1 = NewSearcher(Reader);
            Searcher2 = NewSearcher(Reader);
            writer.Dispose();
        }
        public static void ApplyData(string fileName)
        {
            List<IndexAction> indexOperations = new List<IndexAction>();
            string line;
            int rowCounter = 0;
            int totalCounter = 0;
            int n;
            double d;

            // Get unique rated movies
            IEnumerable<int> ratedMovies = ImportRatedIDs();

            // Read the file and display it line by line.
            using (StreamReader file = new StreamReader(fileName))
            {
                file.ReadLine();    // Skip header
                while ((line = file.ReadLine()) != null)
                {

                    char[] delimiters = new char[] { '\t' };
                    string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                    // If it is a rated movie, add it
                    if (ratedMovies.Contains(Convert.ToInt32(parts[0])))
                    {
                        Document doc = new Document();
                        doc.Add("id", Convert.ToString(parts[0]));
                        doc.Add("title", Convert.ToString(parts[1]));
                        doc.Add("imdbID", Convert.ToInt32(parts[2]));
                        doc.Add("spanishTitle", Convert.ToString(parts[3]));
                        doc.Add("imdbPictureURL", Convert.ToString(parts[4]));

                        if (int.TryParse(parts[5], out n))
                            doc.Add("year", Convert.ToInt32(parts[5]));
                        doc.Add("rtID", Convert.ToString(parts[6]));

                        if (double.TryParse(parts[7], out d))
                            doc.Add("rtAllCriticsRating", Convert.ToDouble(parts[7]));

                        indexOperations.Add(new IndexAction(IndexActionType.Upload, doc));
                        rowCounter++;
                        totalCounter++;
                        if (rowCounter == 1000)
                        {
                            IndexClient.Documents.Index(new IndexBatch(indexOperations));
                            indexOperations.Clear();
                            Console.WriteLine("Uploaded {0} docs...", totalCounter);
                            rowCounter = 0;
                        }
                    }
                }
                if (rowCounter > 0)
                {
                    Console.WriteLine("Uploading {0} docs...", rowCounter);
                    IndexClient.Documents.Index(new IndexBatch(indexOperations));
                }

                file.Close();
            }
        }
        public virtual void TestBasic()
        {

            AssumeTrue("Test requires SortedSetDV support", DefaultCodecSupportsSortedSet());
            Directory dir = NewDirectory();

            FacetsConfig config = new FacetsConfig();
            config.SetMultiValued("a", true);
            RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);

            Document doc = new Document();
            doc.Add(new SortedSetDocValuesFacetField("a", "foo"));
            doc.Add(new SortedSetDocValuesFacetField("a", "bar"));
            doc.Add(new SortedSetDocValuesFacetField("a", "zoo"));
            doc.Add(new SortedSetDocValuesFacetField("b", "baz"));
            writer.AddDocument(config.Build(doc));
            if (Random().NextBoolean())
            {
                writer.Commit();
            }

            doc = new Document();
            doc.Add(new SortedSetDocValuesFacetField("a", "foo"));
            writer.AddDocument(config.Build(doc));

            // NRT open
            IndexSearcher searcher = NewSearcher(writer.Reader);

            // Per-top-reader state:
            SortedSetDocValuesReaderState state = new DefaultSortedSetDocValuesReaderState(searcher.IndexReader);

            FacetsCollector c = new FacetsCollector();

            searcher.Search(new MatchAllDocsQuery(), c);

            SortedSetDocValuesFacetCounts facets = new SortedSetDocValuesFacetCounts(state, c);

            Assert.AreEqual("dim=a path=[] value=4 childCount=3\n  foo (2)\n  bar (1)\n  zoo (1)\n", facets.GetTopChildren(10, "a").ToString());
            Assert.AreEqual("dim=b path=[] value=1 childCount=1\n  baz (1)\n", facets.GetTopChildren(10, "b").ToString());

            // DrillDown:
            DrillDownQuery q = new DrillDownQuery(config);
            q.Add("a", "foo");
            q.Add("b", "baz");
            TopDocs hits = searcher.Search(q, 1);
            Assert.AreEqual(1, hits.TotalHits);

            IOUtils.Close(writer, searcher.IndexReader, dir);
        }
Example #18
0
        public virtual void TestBinaryFieldInIndex()
        {
            FieldType ft = new FieldType();
            ft.Stored = true;
            IndexableField binaryFldStored = new StoredField("binaryStored", (sbyte[])(Array)System.Text.UTF8Encoding.UTF8.GetBytes(BinaryValStored));
            IndexableField stringFldStored = new Field("stringStored", BinaryValStored, ft);

            Document doc = new Document();

            doc.Add(binaryFldStored);

            doc.Add(stringFldStored);

            /// <summary>
            /// test for field count </summary>
            Assert.AreEqual(2, doc.Fields.Count);

            /// <summary>
            /// add the doc to a ram index </summary>
            Directory dir = NewDirectory();
            Random r = new Random();
            RandomIndexWriter writer = new RandomIndexWriter(r, dir);
            writer.AddDocument(doc);

            /// <summary>
            /// open a reader and fetch the document </summary>
            IndexReader reader = writer.Reader;
            Document docFromReader = reader.Document(0);
            Assert.IsTrue(docFromReader != null);

            /// <summary>
            /// fetch the binary stored field and compare it's content with the original one </summary>
            BytesRef bytes = docFromReader.GetBinaryValue("binaryStored");
            Assert.IsNotNull(bytes);

            string binaryFldStoredTest = Encoding.UTF8.GetString((byte[])(Array)bytes.Bytes).Substring(bytes.Offset, bytes.Length);
            //new string(bytes.Bytes, bytes.Offset, bytes.Length, IOUtils.CHARSET_UTF_8);
            Assert.IsTrue(binaryFldStoredTest.Equals(BinaryValStored));

            /// <summary>
            /// fetch the string field and compare it's content with the original one </summary>
            string stringFldStoredTest = docFromReader.Get("stringStored");
            Assert.IsTrue(stringFldStoredTest.Equals(BinaryValStored));

            writer.Dispose();
            reader.Dispose();
            dir.Dispose();
        }
 private void button2_Click(object sender, EventArgs e)
 {
     BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
     iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, BaseColor.DARK_GRAY);
     Document doc = new Document(iTextSharp.text.PageSize.LETTER,10,10,42,42);
     PdfWriter pdw = PdfWriter.GetInstance(doc, new FileStream(naziv + ".pdf", FileMode.Create));
     doc.Open();
     Paragraph p = new Paragraph("Word Count for : "+naziv,times);
     doc.Add(p);
     p.Alignment = 1;
     PdfPTable pdt = new PdfPTable(2);
     pdt.HorizontalAlignment = 1;
     pdt.SpacingBefore = 20f;
     pdt.SpacingAfter = 20f;
     pdt.AddCell("Word");
     pdt.AddCell("No of repetitions");
     foreach (Rijec r in lista_rijeci)
     {
         pdt.AddCell(r.Tekst);
         pdt.AddCell(Convert.ToString(r.Ponavljanje));
     }
     using (MemoryStream stream = new MemoryStream())
     {
         chart1.SaveImage(stream, ChartImageFormat.Png);
         iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
         chartImage.ScalePercent(75f);
         chartImage.Alignment = 1;
         doc.Add(chartImage);
     }
     doc.Add(pdt);
     doc.Close();
     MessageBox.Show("PDF created!");
 }
Example #20
0
        private void AusgangsrechnungenPDF_Click(object sender, EventArgs e)
        {
            string pdfString = "";
            Document pdfDoc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "\\exportAusgangsrechnungen.pdf",
               System.IO.FileMode.Create));

            pdfDoc.Open();

            foreach (DataGridViewRow row in dataGridViewAusgangsrechnung.SelectedRows)
            {

                foreach(DataGridViewCell cell in row.Cells)
                {

                    pdfString += cell.Value.ToString() + " ";
                }
                pdfDoc.Add(new Paragraph (pdfString));
                pdfString = "";

            }

            PdfContentByte cb = writer.DirectContent;
            cb.MoveTo(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height);
            cb.LineTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height);
            cb.Stroke();

            pdfDoc.Close();
        }
Example #21
0
        public override void SetUp()
        {
            base.SetUp();
            // we generate aweful regexps: good for testing.
            // but for preflex codec, the test can be very slow, so use less iterations.
            NumIterations = Codec.Default.Name.Equals("Lucene3x") ? 10 * RANDOM_MULTIPLIER : AtLeast(50);
            Dir = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.KEYWORD, false)).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000)));
            Document doc = new Document();
            Field field = NewStringField("field", "", Field.Store.YES);
            doc.Add(field);
            Terms = new SortedSet<BytesRef>();

            int num = AtLeast(200);
            for (int i = 0; i < num; i++)
            {
                string s = TestUtil.RandomUnicodeString(Random());
                field.StringValue = s;
                Terms.Add(new BytesRef(s));
                writer.AddDocument(doc);
            }

            TermsAutomaton = BasicAutomata.MakeStringUnion(Terms);

            Reader = writer.Reader;
            Searcher = NewSearcher(Reader);
            writer.Dispose();
        }
Example #22
0
        virtual public void FileSpecCheckTest2() {
            Document document = new Document();
            PdfAWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest2.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B);
            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
            document.Add(new Paragraph("Hello World", font));

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            MemoryStream txt = new MemoryStream();
            StreamWriter outp = new StreamWriter(txt);
            outp.Write("<foo><foo2>Hello world</foo2></foo>");
            outp.Close();

            PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, null, "foo.xml", txt.ToArray());
            fs.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Unspecified);

            writer.AddFileAttachment(fs);

            document.Close();
        }
Example #23
0
        virtual public void CreatePdfTest() {
            String fileName = "xmp_metadata.pdf";
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create));
            MemoryStream os = new MemoryStream();
            XmpWriter xmp = new XmpWriter(os, XmpWriter.UTF16, 2000);

            DublinCoreProperties.AddSubject(xmp.XmpMeta, "Hello World");
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "XMP & Metadata");
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "Metadata");

            PdfProperties.SetKeywords(xmp.XmpMeta, "Hello World, XMP & Metadata, Metadata");
            PdfProperties.SetVersion(xmp.XmpMeta, "1.4");

            xmp.Close();

            writer.XmpMetadata = os.ToArray();
            // step 3
            document.Open();
            // step 4
            document.Add(new Paragraph("Hello World"));
            // step 5
            document.Close();

            CompareResults(fileName, fileName);
        }
Example #24
0
        private void btnButtonPDF_Click(object sender, EventArgs e)
        {
        //path to save to your desktop
            sfd.Title = "Save As PDF";
            sfd.Filter = "PDF|.PDF";
            sfd.InitialDirectory = @"C:\Users\RunningEXE\Desktop";

            sfd.InitialDirectory = @"C:\Users\Anthony J. Fiori\Desktop";


        //pops up the dialog box to actually save
            if (sfd.ShowDialog() == DialogResult.OK)
            { 
            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
            //pushes out notification when PDF is created
            MessageBox.Show("PDF Saved to " + wri);

            MessageBox.Show("PDF Created");

            doc.Open();//Open Document to write
            //write some content
            Paragraph paragraph = new Paragraph(txtInfo.Text +" "+ "This is my firest line using paragraph. ");
            //now add the above created text using different class object to our pdf document
            doc.Add(paragraph);
            doc.Close();//close document
            }
        }
Example #25
0
		public override void Visit(Document document)
		{
			var directoryAttribute = document.Attributes.FirstOrDefault(a => a.Name == "docdir");
			if (directoryAttribute != null)
			{
				document.Attributes.Remove(directoryAttribute);
			}

			// check if this document has generated includes to other files
			var includeAttribute = document.Attributes.FirstOrDefault(a => a.Name == "includes-from-dirs");

			if (includeAttribute != null)
			{
				var thisFileUri = new Uri(_destination.FullName);
				var directories = includeAttribute.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

				foreach (var directory in directories)
				{
					foreach (var file in Directory.EnumerateFiles(Path.Combine(Program.OutputDirPath, directory), "*.asciidoc", SearchOption.AllDirectories))
					{
						var fileInfo = new FileInfo(file);
						var referencedFileUri = new Uri(fileInfo.FullName);
						var relativePath = thisFileUri.MakeRelativeUri(referencedFileUri);
						var include = new Include(relativePath.OriginalString);

						document.Add(include);
					}
				}
			}

			base.Visit(document);
		}
Example #26
0
        virtual public void TestCreatePdfA_2()
        {
            bool exceptionThrown = false;
            Document document;
            PdfAWriter writer;
            try
            {
                string filename = OUT + "TestCreatePdfA_1.pdf";
                FileStream fos = new FileStream(filename, FileMode.Create);

                document = new Document();

                writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_1A);
                writer.CreateXmpMetadata();

                document.Open();

                Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 12, Font.BOLD);
                document.Add(new Paragraph("Hello World", font));

                FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
                ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
                iccProfileFileStream.Close();

                writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
                document.Close();
            }
            catch (PdfAConformanceException)
            {
                exceptionThrown = true;
            }
            if (!exceptionThrown)
                Assert.Fail("PdfAConformance exception should be thrown");
        }
Example #27
0
        public void TestCreatePdfA_1()
        {
            Document document = null;
            PdfAWriter writer = null;
            try
            {
                string filename = OUT + "TestCreatePdfA_1.pdf";
                FileStream fos = new FileStream(filename, FileMode.Create);

                document = new Document();

                writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_1B);
                writer.CreateXmpMetadata();

                document.Open();

                Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
                document.Add(new Paragraph("Hello World", font));

                FileStream iccProfileFileStream = new FileStream(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open);
                ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
                iccProfileFileStream.Close();

                writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
                document.Close();
            }
            catch (PdfAConformanceException e)
            {
                Assert.Fail("PdfAConformance exception should not be thrown: " + e.Message);
            }
        }
Example #28
0
        public void ImageCheckTest1()
        {
            string filename = OUT + "ImageCheckTest1.pdf";
            FileStream fos = new FileStream(filename, FileMode.Create);
            Document document = new Document();
            PdfWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_2A);
            document.Open();

            String[] pdfaErrors = new String[9];
            for (int i = 1; i <= 9; i++)
            {
                try
                {
                    Image img = Image.GetInstance(String.Format("{0}jpeg2000\\file{1}.jp2", RESOURCES, i));
                    document.Add(img);
                    document.NewPage();
                }
                catch (Exception e)
                {
                    pdfaErrors[i - 1] = e.Message;
                }
            }

            Assert.AreEqual(null, pdfaErrors[0]);
            Assert.AreEqual(null, pdfaErrors[1]);
            Assert.AreEqual(null, pdfaErrors[2]);
            Assert.AreEqual(null, pdfaErrors[3]);
            Assert.AreEqual(true, pdfaErrors[4].Contains("0x01"));
            Assert.AreEqual(null, pdfaErrors[5]);
            Assert.AreEqual(true, pdfaErrors[6].Contains("0x01"));
            Assert.AreEqual(null, pdfaErrors[7]);
            Assert.AreEqual(null, pdfaErrors[8]);

            document.Close();
        }
Example #29
0
 public void GenerarDocumento(Document document)
 {
     int i, j;
     PdfPTable datatable = new PdfPTable(dataGridView1.ColumnCount);
     datatable.DefaultCell.Padding = 3;
     float[] headerwidths = GetTamañoColumnas(dataGridView1);
     datatable.SetWidths(headerwidths);
     datatable.WidthPercentage = 100;
     datatable.DefaultCell.BorderWidth = 2;
     datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
     for (i = 0; i < dataGridView1.ColumnCount; i++)
     {
         datatable.AddCell(dataGridView1.Columns[i].HeaderText);
     }
     datatable.HeaderRows = 1;
     datatable.DefaultCell.BorderWidth = 1;
     for (i = 0; i < dataGridView1.Rows.Count; i++)
     {
         for (j = 0; j < dataGridView1.Columns.Count; j++)
         {
             if (dataGridView1[j, i].Value != null)
             {
                 datatable.AddCell(new Phrase(dataGridView1[j, i].Value.ToString()));//En esta parte, se esta agregando un renglon por cada registro en el datagrid
             }
         }
         datatable.CompleteRow();
     }
     document.Add(datatable);
 }
Example #30
0
        public override void SetUp()
        {
            base.SetUp();
            Dir = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000)));

            Document doc = new Document();
            Field field = NewStringField("field", "", Field.Store.NO);
            doc.Add(field);

            NumberFormatInfo df = new NumberFormatInfo();
            df.NumberDecimalDigits = 0;

            //NumberFormat df = new DecimalFormat("000", new DecimalFormatSymbols(Locale.ROOT));
            for (int i = 0; i < 1000; i++)
            {
                field.StringValue = i.ToString(df);
                writer.AddDocument(doc);
            }

            Reader = writer.Reader;
            Searcher = NewSearcher(Reader);
            writer.Dispose();
            if (VERBOSE)
            {
                Console.WriteLine("TEST: setUp searcher=" + Searcher);
            }
        }
Example #31
0
        public virtual void TestTermUTF16SortOrder()
        {
            Random            rnd    = Random();
            Directory         dir    = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(rnd, dir, Similarity, TimeZone);
            Document          d      = new Document();
            // Single segment
            Field f = NewStringField("f", "", Field.Store.NO);

            d.Add(f);
            char[]           chars    = new char[2];
            HashSet <string> allTerms = new HashSet <string>();

            int num = AtLeast(200);

            for (int i = 0; i < num; i++)
            {
                string s;
                if (rnd.NextBoolean())
                {
                    // Single char
                    if (rnd.NextBoolean())
                    {
                        // Above surrogates
                        chars[0] = (char)GetInt(rnd, 1 + UnicodeUtil.UNI_SUR_LOW_END, 0xffff);
                    }
                    else
                    {
                        // Below surrogates
                        chars[0] = (char)GetInt(rnd, 0, UnicodeUtil.UNI_SUR_HIGH_START - 1);
                    }
                    s = new string(chars, 0, 1);
                }
                else
                {
                    // Surrogate pair
                    chars[0] = (char)GetInt(rnd, UnicodeUtil.UNI_SUR_HIGH_START, UnicodeUtil.UNI_SUR_HIGH_END);
                    Assert.IsTrue(((int)chars[0]) >= UnicodeUtil.UNI_SUR_HIGH_START && ((int)chars[0]) <= UnicodeUtil.UNI_SUR_HIGH_END);
                    chars[1] = (char)GetInt(rnd, UnicodeUtil.UNI_SUR_LOW_START, UnicodeUtil.UNI_SUR_LOW_END);
                    s        = new string(chars, 0, 2);
                }
                allTerms.Add(s);
                f.StringValue = s;

                writer.AddDocument(d);

                if ((1 + i) % 42 == 0)
                {
                    writer.Commit();
                }
            }

            IndexReader r = writer.Reader;

            // Test each sub-segment
            foreach (AtomicReaderContext ctx in r.Leaves)
            {
                CheckTermsOrder(ctx.Reader, allTerms, false);
            }
            CheckTermsOrder(r, allTerms, true);

            // Test multi segment
            r.Dispose();

            writer.ForceMerge(1);

            // Test single segment
            r = writer.Reader;
            CheckTermsOrder(r, allTerms, true);
            r.Dispose();

            writer.Dispose();
            dir.Dispose();
        }
Example #32
0
        protected virtual Document CreateDocument(SearchEngineEntry post)
        {
            var doc = new Document();

            var field = new Field(Entryid,
                                  NumericUtils.IntToPrefixCoded(post.EntryId),
                                  Field.Store.YES,
                                  Field.Index.NOT_ANALYZED,
                                  Field.TermVector.NO);

            doc.Add(field);

            field = new Field(Categories, post.Categories, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES);
            doc.Add(field);

            field = new Field(Colors, post.Colors, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES);
            doc.Add(field);

            field = new Field(Silouhettes, post.Silouhettes, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES);
            doc.Add(field);

            field = new Field(Fabrics, post.Fabrics, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES);
            doc.Add(field);

            field = new Field(Seasons, post.Seasons, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES);
            doc.Add(field);

            field = new Field(EventTypes, post.EventTypes, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES);
            doc.Add(field);

            field = new Field(Tags, post.Tags, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES);
            doc.Add(field);

            field = new Field(Tags, (post.LastWornDate != null) ?
                              post.LastWornDate.Value.ToString("yyyyMMdd", CultureInfo.InvariantCulture)
                : string.Empty,
                              Field.Store.NO,
                              Field.Index.ANALYZED,
                              Field.TermVector.YES);
            doc.Add(field);

            // Boolean field just 1/0 on a text field
            field = new Field(CreatedByMe,
                              Convert.ToInt32(post.CreatedByMe).ToString(),
                              Field.Store.NO,
                              Field.Index.NOT_ANALYZED,
                              Field.TermVector.NO);
            doc.Add(field);

            field = new Field(IsUpToDate,
                              Convert.ToInt32(post.IsUpToDate).ToString(),
                              Field.Store.NO,
                              Field.Index.NOT_ANALYZED,
                              Field.TermVector.NO);
            doc.Add(field);

            NumericField fieldNumber = new NumericField(FlavorId).SetIntValue(post.FlavorId);

            doc.Add(fieldNumber);

            fieldNumber = new NumericField(MyRating).SetIntValue(post.MyRating);
            doc.Add(fieldNumber);

            fieldNumber = new NumericField(EditorRating).SetIntValue(post.EditorRating);
            doc.Add(fieldNumber);

            fieldNumber = new NumericField(FriendRating).SetIntValue(post.FriendRating);
            doc.Add(fieldNumber);

            return(doc);
        }
Example #33
0
        private void CreateColoredTablesFile(string outPath, bool tagged)
        {
            Document  document = new Document();
            PdfWriter writer   = PdfWriter.GetInstance(document, File.Create(outPath));

            if (tagged)
            {
                writer.SetTagged();
            }
            document.Open();

            BaseColor color       = new BaseColor(255, 255, 240);
            Font      coloredFont = new Font(Font.FontFamily.HELVETICA, 12f, Font.NORMAL, color);

            //First table
            PdfPTable table      = new PdfPTable(4);
            int       rowsNum    = 10;
            int       columnsNum = 4;

            for (int i = 0; i < rowsNum; ++i)
            {
                for (int j = 0; j < columnsNum; ++j)
                {
                    PdfPCell cell = new PdfPCell(new Paragraph("text", coloredFont));
                    cell.BorderWidth     = 2;
                    cell.BorderColor     = BaseColor.DARK_GRAY;
                    cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                    table.AddCell(cell);
                }
            }
            document.Add(table);
            document.NewPage();


            Font fontRed   = new Font(Font.FontFamily.HELVETICA, 12f, Font.NORMAL, new BaseColor(255, 0, 0));
            Font fontGreen = new Font(Font.FontFamily.HELVETICA, 12f, Font.NORMAL, new BaseColor(0, 255, 0));
            Font fontBlue  = new Font(Font.FontFamily.HELVETICA, 12f, Font.NORMAL, new BaseColor(0, 0, 255));

            //Second table
            table = new PdfPTable(4);

            PdfPCell cell11 = new PdfPCell(new Paragraph("text", fontRed));
            PdfPCell cell12 = new PdfPCell(new Paragraph("text", fontBlue));
            PdfPCell cell13 = new PdfPCell(new Paragraph("text", fontGreen));


            PdfPCell cell21 = new PdfPCell(new Paragraph("text", fontRed));
            PdfPCell cell22 = new PdfPCell(new Paragraph("text", fontGreen));
            PdfPCell cell23 = new PdfPCell(new Paragraph("text", fontBlue));

            PdfPCell cell32 = new PdfPCell(new Paragraph("text", fontBlue));
            PdfPCell cell33 = new PdfPCell(new Paragraph("text", fontRed));
            PdfPCell cell34 = new PdfPCell(new Paragraph("text", fontGreen));

            table.AddCell(cell11);
            table.AddCell(cell12);
            table.AddCell(cell13);

            table.AddCell(cell21);
            table.AddCell(cell22);
            table.AddCell(cell23);

            table.AddCell(cell32);
            table.AddCell(cell33);
            table.AddCell(cell34);

            document.Add(table);

            document.Add(new Phrase("  "));

            //Third table
            table = new PdfPTable(4);

            cell11 = new PdfPCell(new Paragraph("text", fontRed));
            cell11.BackgroundColor = BaseColor.YELLOW;
            cell11.BorderWidth     = 3;
            cell11.BorderColor     = new BaseColor(0, 0, 255);
            cell12 = new PdfPCell(new Paragraph("text", fontBlue));
            cell13 = new PdfPCell(new Paragraph("text", fontGreen));


            cell21 = new PdfPCell(new Paragraph("text", fontRed));
            cell21.BackgroundColor = BaseColor.LIGHT_GRAY;
            cell21.BorderColor     = BaseColor.PINK;
            cell21.BorderWidth     = 3;
            cell22 = new PdfPCell(new Paragraph("text", fontGreen));
            cell22.BackgroundColor = BaseColor.YELLOW;
            cell22.BorderColor     = BaseColor.BLUE;
            cell22.BorderWidth     = 3;
            cell23 = new PdfPCell(new Paragraph("text", fontBlue));
            cell23.BackgroundColor = BaseColor.GREEN;
            cell23.BorderWidth     = 3;
            cell23.BorderColor     = BaseColor.WHITE;

            cell32 = new PdfPCell(new Paragraph("text", fontBlue));
            cell32.BackgroundColor = BaseColor.LIGHT_GRAY;
            cell32.BorderColor     = BaseColor.MAGENTA;
            cell32.BorderWidth     = 3;
            cell33 = new PdfPCell(new Paragraph("text", fontRed));
            cell33.BackgroundColor = BaseColor.PINK;
            cell33.BorderColor     = BaseColor.CYAN;
            cell33.BorderWidth     = 3;
            cell34 = new PdfPCell(new Paragraph("text", fontGreen));
            cell34.BackgroundColor = BaseColor.ORANGE;
            cell34.BorderColor     = BaseColor.WHITE;
            cell34.BorderWidth     = 3;

            table.AddCell(cell11);
            table.AddCell(cell12);
            table.AddCell(cell13);

            table.AddCell(cell21);
            table.AddCell(cell22);
            table.AddCell(cell23);

            table.AddCell(cell32);
            table.AddCell(cell33);
            table.AddCell(cell34);

            document.Add(table);

            document.Close();
        }
Example #34
0
        public FileResult GenerarPdf()
        {
            Document doc = new Document();               //Creamos documento pdf

            byte[] buffer;                               //Los bytes donde se almacenara el pdf

            using (MemoryStream ms = new MemoryStream()) //guardamos en memoria
            {
                PdfWriter.GetInstance(doc, ms);
                doc.Open();

                Paragraph title = new Paragraph("Lista Marca"); //titulo del pdf
                title.Alignment = Element.ALIGN_CENTER;
                doc.Add(title);                                 //Agregamos al documento

                Paragraph espacio = new Paragraph(" ");         //titulo del pdf
                espacio.Alignment = Element.ALIGN_CENTER;
                doc.Add(espacio);                               //Agregamos al documento un espacio en blanco



                PdfPTable table = new PdfPTable(3);  //Creamos una tabla con sus # de columnas

                //Columnas
                float[] values = new float[3] {
                    30, 40, 80
                };                                             //Definimos ancho de columnas de la tabla
                table.SetWidths(values);

                //Celdas
                PdfPCell celda1 = new PdfPCell(new Paragraph("Id Marca"));
                celda1.BackgroundColor     = new BaseColor(130, 130, 130);
                celda1.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table.AddCell(celda1);

                PdfPCell celda2 = new PdfPCell(new Paragraph("Nombre"));
                celda2.BackgroundColor     = new BaseColor(130, 130, 130);
                celda2.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table.AddCell(celda2);

                PdfPCell celda3 = new PdfPCell(new Paragraph("Descripcion"));
                celda3.BackgroundColor     = new BaseColor(130, 130, 130);
                celda3.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table.AddCell(celda3);

                List <MarcaCLS> listaMarca   = (List <MarcaCLS>)Session["listaMarca"]; //Objeto session que esta cuando se obtiene la lista de marca
                int             numRegistros = listaMarca.Count();

                for (int i = 0; i < numRegistros; i++)
                {
                    table.AddCell(listaMarca[i].iidmarca.ToString());
                    table.AddCell(listaMarca[i].nombre.ToString());
                    table.AddCell(listaMarca[i].descripcion.ToString());
                }


                doc.Add(table);
                doc.Close();


                buffer = ms.ToArray();
            }

            return(File(buffer, "application/pdf"));
        }
Example #35
0
        public ActionResult Printaj(int id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Racuni r = db.RacuniDbSet.Find(id);

            if (r == null)
            {
                return(HttpNotFound());
            }


            RacunPrintajVM model = db.RacuniDbSet
                                   .Where(x => x.Id == id)
                                   .Select(f => new RacunPrintajVM
            {
                Id             = f.Id,
                Placen         = f.Placen ? "DA" : "NE",
                DatumIzdavanja = f.DatumIzdavanja,
                KorisnikId     = f.KorisnikId,
                PeriodDo       = f.ObracunskiPeriodDO,
                PeriodOd       = f.ObracunskiPeriodOD,
                RokPlacanja    = f.RokPlacanja,
                Sifra          = f.Sifra,
                Ukupno         = f.UkupnoBezPDV.ToString(),
                PDF            = (f.UkupnoSaPDV - f.UkupnoBezPDV).ToString(),
                UkupnoPDV      = f.UkupnoSaPDV.ToString(),
            }).Single();



            model.Korisnik    = db.KorisnikDbSet.Find(model.KorisnikId);
            model.ListaStavki = db.RacuniStavkeDbSet.Where(g => g.RacunId == model.Id).ToList();



            PdfPTable pdftabela    = new PdfPTable(2);
            PdfPTable tabela3      = new PdfPTable(3);
            PdfPTable tabelaUsluge = new PdfPTable(7);
            PdfPTable tabelaTotal  = new PdfPTable(5);


            PdfPCell celija;

            string FONT = "c:/Windows/Fonts/arial.ttf";
            Font   font = FontFactory.GetFont(FONT, BaseFont.IDENTITY_H, true);

            using (MemoryStream ms = new MemoryStream())
            {
                Document document = new Document();

                document.SetPageSize(PageSize.A4);
                document.SetMargins(50f, 50f, 20f, 20f);


                pdftabela.WidthPercentage     = 100;
                pdftabela.HorizontalAlignment = Element.ALIGN_LEFT;


                tabela3.WidthPercentage     = 100;
                tabela3.HorizontalAlignment = Element.ALIGN_LEFT;

                tabelaUsluge.WidthPercentage     = 100;
                tabelaUsluge.HorizontalAlignment = Element.ALIGN_LEFT;

                tabelaTotal.WidthPercentage     = 100;
                tabelaTotal.HorizontalAlignment = Element.ALIGN_LEFT;

                PdfWriter writer = PdfWriter.GetInstance(document, ms);
                document.Open();

                BaseFont nf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false);
                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false);

                var Sivaboja = new BaseColor(25, 25, 25);

                Font fontsadrzaj = new Font(nf, 11);
                Font font8       = new Font(nf, 8);
                Font font8bold   = new Font(bf, 8);
                Font font11      = new Font(nf, 11);
                Font font9       = new Font(nf, 9);
                Font font10      = new Font(nf, 10);
                Font font11bold  = new Font(bf, 11);
                Font font16Bold  = new Font(bf, 16);
                Font font16      = new Font(nf, 16);
                Font font20      = new Font(nf, 18);

                string putanja = Server.MapPath("~/Slike/");
                Image  header  = Image.GetInstance(putanja + "header.png");

                //////////////////////////////////////////////////////////////////////////

                header.ScaleToFit(PageSize.A4.Width - 90f, 80f);
                header.SpacingBefore = 10f;
                header.SpacingAfter  = 10f;
                header.Alignment     = Element.ALIGN_LEFT;
                document.Add(header);

                //////////////////////////////////////////////////////////////////////////

                pdftabela.SetWidths(new float[] { 160f, 100f });
                tabela3.SetWidths(new float[] { 50, 40, 50 });
                tabelaUsluge.SetWidths(new float[] { 35, 35, 35, 35, 35, 35, 35 });
                tabelaTotal.SetWidths(new float[] { 50, 50, 50, 50, 50 });



                #region tijelo

                pdftabela.SpacingBefore = 50f;


                celija = new PdfPCell(new Phrase("RAČUN - " + model.Sifra, font20));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                pdftabela.AddCell(celija);


                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                pdftabela.AddCell(celija);

                //celija = new PdfPCell(new Phrase("Sifra " + model.Sifra, font11));
                //celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                //celija.VerticalAlignment = Element.ALIGN_MIDDLE;
                //celija.BackgroundColor = BaseColor.WHITE;
                //celija.Border = Rectangle.NO_BORDER;
                //pdftabela.AddCell(celija);


                tabela3.SpacingBefore = 50f;


                #endregion


                document.Add(pdftabela);



                celija = new PdfPCell(new Phrase("Klijent: ", font11bold));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 25f;
                tabela3.AddCell(celija);

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                celija = new PdfPCell(new Phrase("Detalji o računu: ", font11bold));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.MinimumHeight       = 25f;
                celija.PaddingLeft         = 20;
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                tabela3.CompleteRow();



                celija = new PdfPCell(new Phrase(model.Korisnik.Ime + " " + model.Korisnik.Prezime, font11));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 16f;
                tabela3.AddCell(celija);

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                celija = new PdfPCell(new Phrase("Datum izdavanja: " + model.DatumIzdavanja.ToShortDateString(), font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.MinimumHeight       = 16f;
                celija.PaddingLeft         = 20;
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                tabela3.CompleteRow();



                celija = new PdfPCell(new Phrase(model.Korisnik.Adresa + " ", font11));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 16f;
                tabela3.AddCell(celija);


                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                celija = new PdfPCell(new Phrase("Period od: " + model.PeriodOd.ToShortDateString(), font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.PaddingLeft         = 20;
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                tabela3.CompleteRow();



                celija = new PdfPCell(new Phrase(model.Korisnik.Naselje + ", " + model.Korisnik.Opcina.NazivOpcine, font11));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 16f;
                tabela3.AddCell(celija);


                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                celija = new PdfPCell(new Phrase("Period od: " + model.PeriodDo.ToShortDateString(), font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.PaddingLeft         = 20;
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                tabela3.CompleteRow();

                document.Add(tabela3);



                tabelaUsluge.SpacingBefore = 50f;



                celija = new PdfPCell(new Phrase("USLUGA ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("NAZIV ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("DATUM OD ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("DATUM DO ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("CIJENA ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("PDV ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("UKUPNO ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);


                /////////////////////////////////////////////////////////////////
                tabelaUsluge.CompleteRow();
                /////////////////////////////////////////////////////////////////


                celija = new PdfPCell(new Phrase("PROŠIRENI ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("TV ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("01.10.2018 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("31.10.2018 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("15,35 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("3,63 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("18,99 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                ////////////////////////////////////////////////////////////////////////
                tabelaUsluge.CompleteRow();
                ///////////////////////////////////////////////////////////////////////////

                celija = new PdfPCell(new Phrase("PROŠIRENI ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("TV ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("01.10.2018 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("31.10.2018 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("15,35 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("3,63 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("18,99 ", font11));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                tabelaUsluge.CompleteRow();
                document.Add(tabelaUsluge);

                ////////////////////////////////////////////////////////////////////////


                tabelaTotal.SpacingBefore = 100f;

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);


                celija = new PdfPCell(new Phrase("Ukupno bez PDV", font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija = new PdfPCell(new Phrase("PDV 17%", font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija = new PdfPCell(new Phrase("Ukupno sa PDV", font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                tabelaTotal.CompleteRow();

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);


                celija = new PdfPCell(new Phrase("55.27 KM", font16));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija = new PdfPCell(new Phrase("6.92 KM", font16));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija = new PdfPCell(new Phrase("59.49 KM", font16Bold));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                tabelaTotal.CompleteRow();

                document.Add(tabelaTotal);



                document.Close();

                byte[] bytes = ms.ToArray();
                ms.Close();



                return(File(bytes, "application/pdf"));
            }
        }
Example #36
0
        public Chap0907()
        {
            Console.WriteLine("Chapter 9 example 7: Barcodes without ttf");

            // step 1: creation of a document-object
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);

            try
            {
                // step 2:
                // we create a writer that listens to the document
                // and directs a PDF-stream to a file

                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap0907.pdf", FileMode.Create));

                // step 3: we open the document
                document.Open();

                // step 4: we add content to the document
                PdfContentByte cb     = writer.DirectContent;
                Barcode39      code39 = new Barcode39();
                code39.Code          = "CODE39-1234567890";
                code39.StartStopText = false;
                Image     image39   = code39.CreateImageWithBarcode(cb, null, null);
                Barcode39 code39ext = new Barcode39();
                code39ext.Code          = "The willows.";
                code39ext.StartStopText = false;
                code39ext.Extended      = true;
                Image      image39ext = code39ext.CreateImageWithBarcode(cb, null, null);
                Barcode128 code128    = new Barcode128();
                code128.Code = "1Z234786 hello";
                Image      image128 = code128.CreateImageWithBarcode(cb, null, null);
                BarcodeEAN codeEAN  = new BarcodeEAN();
                codeEAN.CodeType = BarcodeEAN.EAN13;
                codeEAN.Code     = "9780201615883";
                Image          imageEAN = codeEAN.CreateImageWithBarcode(cb, null, null);
                BarcodeInter25 code25   = new BarcodeInter25();
                code25.GenerateChecksum = true;
                code25.Code             = "41-1200076041-001";
                Image          image25  = code25.CreateImageWithBarcode(cb, null, null);
                BarcodePostnet codePost = new BarcodePostnet();
                codePost.Code = "12345";
                Image          imagePost  = codePost.CreateImageWithBarcode(cb, null, null);
                BarcodePostnet codePlanet = new BarcodePostnet();
                codePlanet.Code     = "50201402356";
                codePlanet.CodeType = BarcodePostnet.PLANET;
                Image       imagePlanet = codePlanet.CreateImageWithBarcode(cb, null, null);
                PdfTemplate tp          = cb.CreateTemplate(0, 0);
                PdfTemplate ean         = codeEAN.CreateTemplateWithBarcode(cb, null, new Color(System.Drawing.Color.Blue));
                BarcodeEAN  codeSUPP    = new BarcodeEAN();
                codeSUPP.CodeType = BarcodeEAN.SUPP5;
                codeSUPP.Code     = "54995";
                codeSUPP.Baseline = -2;
                BarcodeEANSUPP eanSupp      = new BarcodeEANSUPP(codeEAN, codeSUPP);
                Image          imageEANSUPP = eanSupp.CreateImageWithBarcode(cb, null, new Color(System.Drawing.Color.Blue));
                PdfPTable      table        = new PdfPTable(2);
                table.WidthPercentage    = 100;
                table.DefaultCell.Border = Rectangle.NO_BORDER;
                table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                table.DefaultCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                table.DefaultCell.FixedHeight         = 70;
                table.AddCell("CODE 39");
                table.AddCell(new Phrase(new Chunk(image39, 0, 0)));
                table.AddCell("CODE 39 EXTENDED");
                table.AddCell(new Phrase(new Chunk(image39ext, 0, 0)));
                table.AddCell("CODE 128");
                table.AddCell(new Phrase(new Chunk(image128, 0, 0)));
                table.AddCell("CODE EAN");
                table.AddCell(new Phrase(new Chunk(imageEAN, 0, 0)));
                table.AddCell("CODE EAN\nWITH\nSUPPLEMENTAL 5");
                table.AddCell(new Phrase(new Chunk(imageEANSUPP, 0, 0)));
                table.AddCell("CODE INTERLEAVED");
                table.AddCell(new Phrase(new Chunk(image25, 0, 0)));
                table.AddCell("CODE POSTNET");
                table.AddCell(new Phrase(new Chunk(imagePost, 0, 0)));
                table.AddCell("CODE PLANET");
                table.AddCell(new Phrase(new Chunk(imagePlanet, 0, 0)));
                document.Add(table);
            }
            catch (Exception de)
            {
                Console.Error.WriteLine(de.StackTrace);
            }

            // step 5: we close the document
            document.Close();
        }
Example #37
0
        /// <summary>
        /// PDF click event. Generates a PDF with the cochleogram, histogram, sonogram, disparity between cochleae and average activity of the loaded aedat file.
        /// </summary>
        private void Btn_PDF_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog savePDFDialog = new SaveFileDialog();

            savePDFDialog.Title  = "Select a name and a path for the .pdf file";
            savePDFDialog.Filter = "pdf files|*.pdf";
            if (savePDFDialog.ShowDialog() == true)
            {
                this.Cursor = Cursors.Wait;
                Document  doc = new Document();
                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(savePDFDialog.FileName, FileMode.Create));
                doc.SetPageSize(iTextSharp.text.PageSize.A4);
                doc.SetMargins(50, 50, 50, 50);
                doc.Open();

                #region Fonts
                iTextSharp.text.Font fTitle = FontFactory.GetFont("Arial", 30, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                iTextSharp.text.Font fHead  = FontFactory.GetFont("Arial", 18, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                iTextSharp.text.Font fText  = FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                #endregion

                #region Main page
                iTextSharp.text.Paragraph title = new iTextSharp.text.Paragraph("\n\n\n\n\nData Report for " + fileName, fTitle);
                title.Alignment = Element.ALIGN_CENTER;
                doc.Add(title);
                if (settings.PdfS.showDate)
                {
                    iTextSharp.text.Paragraph date = new iTextSharp.text.Paragraph("\n\n" + DateTime.Now);
                    date.Alignment = Element.ALIGN_RIGHT;
                    doc.Add(date);
                }
                #endregion
                if (settings.PdfS.showCochleogram || settings.PdfS.showHistogram)
                {
                    doc.SetMargins(0, 30, 50, 30);
                    doc.NewPage();
                }
                iTextSharp.text.Paragraph paragraph;
                #region Cochleogram
                if (settings.PdfS.showCochleogram)
                {
                    paragraph = new iTextSharp.text.Paragraph("           1. Cochleogram\n\n", fHead);
                    doc.Add(paragraph);
                    paragraph = new iTextSharp.text.Paragraph("                     The following charts represents the cochleogram for both cochleae.\n", fText);
                    doc.Add(paragraph);
                    paragraph = new iTextSharp.text.Paragraph("                         - " + settings.MainS.leftColor + " - Left Cochlea.", fText);
                    doc.Add(paragraph);
                    paragraph = new iTextSharp.text.Paragraph("                         - " + settings.MainS.rightColor + " - Right Cochlea.\n\n\n", fText);
                    doc.Add(paragraph);

                    using (MemoryStream stream = new MemoryStream())
                    {
                        chart_Cochleogram.SaveImage(stream, ImageFormat.Png);
                        iTextSharp.text.Image chartImage2 = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
                        chartImage2.ScaleToFit(iTextSharp.text.PageSize.A4);// ScalePercent(75f);
                        doc.Add(chartImage2);
                    }
                }
                #endregion
                #region Histogram
                if (settings.PdfS.showHistogram)
                {
                    paragraph = new iTextSharp.text.Paragraph("\n           2. Histogram\n\n", fHead);
                    doc.Add(paragraph);
                    using (MemoryStream stream = new MemoryStream())
                    {
                        Histogram spd = new Histogram();
                        spd.chart_Histogram.Width  = 773;
                        spd.chart_Histogram.Height = 350;
                        spd.chart_Histogram.SaveImage(stream, ChartImageFormat.Png);
                        iTextSharp.text.Image chartImage3 = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
                        chartImage3.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 100, iTextSharp.text.PageSize.A4.Height - 200);
                        doc.Add(chartImage3);
                    }
                }
                #endregion
                if (settings.PdfS.showSonogram || settings.PdfS.showDiff)
                {
                    doc.SetMargins(50, 30, 50, 30);
                    doc.NewPage();
                }
                #region Sonogram
                if (settings.PdfS.showSonogram)
                {
                    paragraph = new iTextSharp.text.Paragraph("           3. Sonogram\n\n", fHead);
                    doc.Add(paragraph);
                    using (MemoryStream stream = new MemoryStream())
                    {
                        if (settings.MainS.eventSize == 16)
                        {
                            aedatObject16.generateSonogram("archivobmp", aedatObject16.maxValueSonogram());
                        }
                        else if (settings.MainS.eventSize == 32)
                        {
                            aedatObject32.generateSonogram("archivobmp", aedatObject32.maxValueSonogram());
                        }
                        Sonogram sd = new Sonogram();
                        iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(ImageToBitmap(sd.Img_Sonogram), ImageFormat.Bmp);
                        image1.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 100, iTextSharp.text.PageSize.A4.Height - 200);
                        doc.Add(image1);
                    }
                }
                #endregion
                #region Disparity
                if (settings.PdfS.showDiff && (cochleaInfo == EnumCochleaInfo.STEREO32 || cochleaInfo == EnumCochleaInfo.STEREO64 || cochleaInfo == EnumCochleaInfo.STEREO128 || cochleaInfo == EnumCochleaInfo.STEREO256))
                {
                    paragraph = new iTextSharp.text.Paragraph("\n\n           4. Disparity between cochleae\n\n", fHead);
                    doc.Add(paragraph);
                    paragraph = new iTextSharp.text.Paragraph("                     Disparity between both cochleae.\n", fText);
                    doc.Add(paragraph);
                    paragraph = new iTextSharp.text.Paragraph("                         - Red: left cochlea predominance.", fText);
                    doc.Add(paragraph);
                    paragraph = new iTextSharp.text.Paragraph("                         - Green: right cochlea predominance.\n\n\n", fText);
                    doc.Add(paragraph);
                    using (MemoryStream stream = new MemoryStream())
                    {
                        if (settings.MainS.eventSize == 16)
                        {
                            aedatObject16.generateDisparity("archivobmpDiff", aedatObject16.maxValueSonogram());
                        }

                        else if (settings.MainS.eventSize == 32)
                        {
                            aedatObject32.generateDisparity("archivobmpDiff", aedatObject32.maxValueSonogram());
                        }
                        Difference            sd     = new Difference();
                        iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(ImageToBitmap(sd.Img_Difference), ImageFormat.Bmp);
                        image1.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 100, iTextSharp.text.PageSize.A4.Height - 200);
                        doc.Add(image1);
                    }
                }
                #endregion
                #region Average activity
                if (settings.PdfS.showAverage)
                {
                    doc.SetMargins(0, 30, 50, 30);
                    doc.NewPage();
                    paragraph = new iTextSharp.text.Paragraph("\n\n           5. Average activity of both cochleae\n\n", fHead);
                    doc.Add(paragraph);
                    paragraph = new iTextSharp.text.Paragraph("                     Each dot represents the average of events of a certain time period (Integration Period = " + settings.ToolsS.integrationPeriod.ToString() + " us ).\n", fText);
                    doc.Add(paragraph);
                    using (MemoryStream stream = new MemoryStream())
                    {
                        Average m = new Average();
                        m.chart_Average.Width  = 846;
                        m.chart_Average.Height = 322;
                        m.chart_Average.SaveImage(stream, ChartImageFormat.Png);
                        iTextSharp.text.Image chartImage4 = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
                        chartImage4.ScaleToFit(iTextSharp.text.PageSize.A4);// ScalePercent(75f);
                        doc.Add(chartImage4);
                    }
                }
                #endregion
                doc.Close();

                InfoWindow iw = new InfoWindow("PDF generated", "The PDF file was generated succesfully and it's available at the path you chose");  // Tell the user that the process went OK
                iw.ShowDialog();

                this.Cursor = Cursors.Arrow;
            }
        }
Example #38
0
        public void TestSimpleWithScoring()
        {
            const string idField = "id";
            const string toField = "movieId";

            Directory         dir = NewDirectory();
            RandomIndexWriter w   = new RandomIndexWriter(Random, dir,
                                                          NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))
                                                          .SetMergePolicy(NewLogMergePolicy()));

            // 0
            Document doc = new Document();

            doc.Add(new TextField("description", "A random movie", Field.Store.NO));
            doc.Add(new TextField("name", "Movie 1", Field.Store.NO));
            doc.Add(new TextField(idField, "1", Field.Store.NO));
            w.AddDocument(doc);

            // 1
            doc = new Document();
            doc.Add(new TextField("subtitle", "The first subtitle of this movie", Field.Store.NO));
            doc.Add(new TextField(idField, "2", Field.Store.NO));
            doc.Add(new TextField(toField, "1", Field.Store.NO));
            w.AddDocument(doc);

            // 2
            doc = new Document();
            doc.Add(new TextField("subtitle", "random subtitle; random event movie", Field.Store.NO));
            doc.Add(new TextField(idField, "3", Field.Store.NO));
            doc.Add(new TextField(toField, "1", Field.Store.NO));
            w.AddDocument(doc);

            // 3
            doc = new Document();
            doc.Add(new TextField("description", "A second random movie", Field.Store.NO));
            doc.Add(new TextField("name", "Movie 2", Field.Store.NO));
            doc.Add(new TextField(idField, "4", Field.Store.NO));
            w.AddDocument(doc);
            w.Commit();

            // 4
            doc = new Document();
            doc.Add(new TextField("subtitle", "a very random event happened during christmas night", Field.Store.NO));
            doc.Add(new TextField(idField, "5", Field.Store.NO));
            doc.Add(new TextField(toField, "4", Field.Store.NO));
            w.AddDocument(doc);

            // 5
            doc = new Document();
            doc.Add(new TextField("subtitle", "movie end movie test 123 test 123 random", Field.Store.NO));
            doc.Add(new TextField(idField, "6", Field.Store.NO));
            doc.Add(new TextField(toField, "4", Field.Store.NO));
            w.AddDocument(doc);

            IndexSearcher indexSearcher = new IndexSearcher(w.GetReader());

            w.Dispose();

            // Search for movie via subtitle
            Query joinQuery = JoinUtil.CreateJoinQuery(toField, false, idField,
                                                       new TermQuery(new Term("subtitle", "random")), indexSearcher, ScoreMode.Max);
            TopDocs result = indexSearcher.Search(joinQuery, 10);

            assertEquals(2, result.TotalHits);
            assertEquals(0, result.ScoreDocs[0].Doc);
            assertEquals(3, result.ScoreDocs[1].Doc);

            // Score mode max.
            joinQuery = JoinUtil.CreateJoinQuery(toField, false, idField, new TermQuery(new Term("subtitle", "movie")),
                                                 indexSearcher, ScoreMode.Max);
            result = indexSearcher.Search(joinQuery, 10);
            assertEquals(2, result.TotalHits);
            assertEquals(3, result.ScoreDocs[0].Doc);
            assertEquals(0, result.ScoreDocs[1].Doc);

            // Score mode total
            joinQuery = JoinUtil.CreateJoinQuery(toField, false, idField, new TermQuery(new Term("subtitle", "movie")),
                                                 indexSearcher, ScoreMode.Total);
            result = indexSearcher.Search(joinQuery, 10);
            assertEquals(2, result.TotalHits);
            assertEquals(0, result.ScoreDocs[0].Doc);
            assertEquals(3, result.ScoreDocs[1].Doc);

            //Score mode avg
            joinQuery = JoinUtil.CreateJoinQuery(toField, false, idField, new TermQuery(new Term("subtitle", "movie")),
                                                 indexSearcher, ScoreMode.Avg);
            result = indexSearcher.Search(joinQuery, 10);
            assertEquals(2, result.TotalHits);
            assertEquals(3, result.ScoreDocs[0].Doc);
            assertEquals(0, result.ScoreDocs[1].Doc);

            indexSearcher.IndexReader.Dispose();
            dir.Dispose();
        }
Example #39
0
        private void BtnPrn_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            String date = "";

            date = DateTime.Now.ToString("yyyy-MM-dd");
            DataTable dt = new DataTable();

            dt = ebC.eB20DB.cntDB.selectByDate(date);
            if (dt.Rows.Count <= 0)
            {
                return;
            }

            BaseFont  bfR, bfR1;
            BaseColor clrBlack = new iTextSharp.text.BaseColor(0, 0, 0);
            String    myFont   = Environment.CurrentDirectory + "\\THSarabun.ttf";

            bfR  = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            bfR1 = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfR, 12, iTextSharp.text.Font.NORMAL, clrBlack);
            var logo = iTextSharp.text.Image.GetInstance(Environment.CurrentDirectory + "\\logo.png");

            logo.SetAbsolutePosition(10, PageSize.A4.Height - 90);
            logo.ScaleAbsoluteHeight(70);
            logo.ScaleAbsoluteWidth(70);

            Document doc = new Document(PageSize.A4, 36, 36, 36, 36);

            try
            {
                if (File.Exists(Environment.CurrentDirectory + "\\report.pdf"))
                {
                    File.Delete(Environment.CurrentDirectory + "\\report.pdf");
                }

                FileStream output = new FileStream(Environment.CurrentDirectory + "\\report.pdf", FileMode.Create);
                PdfWriter  writer = PdfWriter.GetInstance(doc, output);
                doc.Open();

                doc.Add(logo);

                int i = 0, r = 0, row2 = 0, rowEnd = 24;
                r = dt.Rows.Count;
                int next = r / 24;
                for (int p = 0; p <= next; p++)
                {
                    PdfContentByte canvas = writer.DirectContent;
                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 12);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "บริษัท เคาเตอร์ พลัส จำกัด", 100, 800, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "99/19 ซอยประเสริฐมนูกิจ 29 ถนนประเสริฐมนูกิจ แขวงจรเข้บัว เขตลาดพร้าว กรุงเทพฯ 10230", 100, 780, 0);
                    canvas.EndText();

                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 18);
                    canvas.ShowTextAligned(Element.ALIGN_CENTER, "รายงานสรุปการนับเงินที่จำหน่ายจากตู้ ตามวันที่ ", PageSize.A4.Width / 2, 740, 0);
                    canvas.EndText();

                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 16);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "ลำดับ ", 60, 720, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "สถานที่ ", 60, 700, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "จำนวนเงินที่นับได้จริง ", 60, 680, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "ยอดรวม ", 360, 720, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "รวมเงิน ", 360, 700, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "เงินเกิน ", 360, 680, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "เงินขาด ", 360, 660, 0);
                    canvas.EndText();

                    canvas.SaveState();
                    canvas.SetLineWidth(0.05f);
                    canvas.MoveTo(40, 640);//vertical
                    canvas.LineTo(40, 110);

                    canvas.MoveTo(40, 640);//Hericental
                    canvas.LineTo(560, 640);

                    canvas.MoveTo(560, 640);//vertical
                    canvas.LineTo(560, 110);

                    canvas.MoveTo(40, 610);//Hericental
                    canvas.LineTo(560, 610);

                    canvas.MoveTo(40, 110);//Hericental
                    canvas.LineTo(560, 110);

                    canvas.MoveTo(100, 640);//vertical
                    canvas.LineTo(100, 110);

                    canvas.MoveTo(400, 640);//vertical
                    canvas.LineTo(400, 110);

                    canvas.MoveTo(440, 640);//vertical QTY
                    canvas.LineTo(440, 110);

                    canvas.MoveTo(500, 640);//vertical Price
                    canvas.LineTo(500, 110);

                    //canvas.MoveTo(520, 640);//vertical Amount
                    //canvas.LineTo(520, 110);
                    canvas.Stroke();
                    canvas.RestoreState();
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                doc.Close();
                System.Threading.Thread.Sleep(1000);

                Process          pp = new Process();
                ProcessStartInfo s  = new ProcessStartInfo(Environment.CurrentDirectory + "\\report.pdf");
                //s.Arguments = "/c dir *.cs";
                pp.StartInfo = s;

                pp.Start();
            }
        }
Example #40
0
        public void TestSimple()
        {
            const string idField = "id";
            const string toField = "productId";

            Directory         dir = NewDirectory();
            RandomIndexWriter w   = new RandomIndexWriter(Random, dir,
                                                          NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))
                                                          .SetMergePolicy(NewLogMergePolicy()));

            // 0
            Document doc = new Document();

            doc.Add(new TextField("description", "random text", Field.Store.NO));
            doc.Add(new TextField("name", "name1", Field.Store.NO));
            doc.Add(new TextField(idField, "1", Field.Store.NO));
            w.AddDocument(doc);

            // 1
            doc = new Document();
            doc.Add(new TextField("price", "10.0", Field.Store.NO));
            doc.Add(new TextField(idField, "2", Field.Store.NO));
            doc.Add(new TextField(toField, "1", Field.Store.NO));
            w.AddDocument(doc);

            // 2
            doc = new Document();
            doc.Add(new TextField("price", "20.0", Field.Store.NO));
            doc.Add(new TextField(idField, "3", Field.Store.NO));
            doc.Add(new TextField(toField, "1", Field.Store.NO));
            w.AddDocument(doc);

            // 3
            doc = new Document();
            doc.Add(new TextField("description", "more random text", Field.Store.NO));
            doc.Add(new TextField("name", "name2", Field.Store.NO));
            doc.Add(new TextField(idField, "4", Field.Store.NO));
            w.AddDocument(doc);
            w.Commit();

            // 4
            doc = new Document();
            doc.Add(new TextField("price", "10.0", Field.Store.NO));
            doc.Add(new TextField(idField, "5", Field.Store.NO));
            doc.Add(new TextField(toField, "4", Field.Store.NO));
            w.AddDocument(doc);

            // 5
            doc = new Document();
            doc.Add(new TextField("price", "20.0", Field.Store.NO));
            doc.Add(new TextField(idField, "6", Field.Store.NO));
            doc.Add(new TextField(toField, "4", Field.Store.NO));
            w.AddDocument(doc);

            IndexSearcher indexSearcher = new IndexSearcher(w.GetReader());

            w.Dispose();

            // Search for product
            Query joinQuery = JoinUtil.CreateJoinQuery(idField, false, toField, new TermQuery(new Term("name", "name2")),
                                                       indexSearcher, ScoreMode.None);

            TopDocs result = indexSearcher.Search(joinQuery, 10);

            assertEquals(2, result.TotalHits);
            assertEquals(4, result.ScoreDocs[0].Doc);
            assertEquals(5, result.ScoreDocs[1].Doc);

            joinQuery = JoinUtil.CreateJoinQuery(idField, false, toField, new TermQuery(new Term("name", "name1")),
                                                 indexSearcher, ScoreMode.None);
            result = indexSearcher.Search(joinQuery, 10);
            assertEquals(2, result.TotalHits);
            assertEquals(1, result.ScoreDocs[0].Doc);
            assertEquals(2, result.ScoreDocs[1].Doc);

            // Search for offer
            joinQuery = JoinUtil.CreateJoinQuery(toField, false, idField, new TermQuery(new Term("id", "5")),
                                                 indexSearcher, ScoreMode.None);
            result = indexSearcher.Search(joinQuery, 10);
            assertEquals(1, result.TotalHits);
            assertEquals(3, result.ScoreDocs[0].Doc);

            indexSearcher.IndexReader.Dispose();
            dir.Dispose();
        }
Example #41
0
        private IndexIterationContext CreateContext(int nDocs, RandomIndexWriter fromWriter, RandomIndexWriter toWriter,
                                                    bool multipleValuesPerDocument, bool scoreDocsInOrder)
        {
            IndexIterationContext context = new IndexIterationContext();
            int numRandomValues           = nDocs / 2;

            context.RandomUniqueValues = new string[numRandomValues];
            ISet <string> trackSet = new JCG.HashSet <string>();

            context.RandomFrom = new bool[numRandomValues];
            for (int i = 0; i < numRandomValues; i++)
            {
                string uniqueRandomValue;
                do
                {
                    uniqueRandomValue = TestUtil.RandomRealisticUnicodeString(Random);
                    //        uniqueRandomValue = TestUtil.randomSimpleString(random);
                } while ("".Equals(uniqueRandomValue, StringComparison.Ordinal) || trackSet.Contains(uniqueRandomValue));
                // Generate unique values and empty strings aren't allowed.
                trackSet.Add(uniqueRandomValue);
                context.RandomFrom[i]         = Random.NextBoolean();
                context.RandomUniqueValues[i] = uniqueRandomValue;
            }

            RandomDoc[] docs = new RandomDoc[nDocs];
            for (int i = 0; i < nDocs; i++)
            {
                string   id       = Convert.ToString(i);
                int      randomI  = Random.Next(context.RandomUniqueValues.Length);
                string   value    = context.RandomUniqueValues[randomI];
                Document document = new Document();
                document.Add(NewTextField(Random, "id", id, Field.Store.NO));
                document.Add(NewTextField(Random, "value", value, Field.Store.NO));

                bool from = context.RandomFrom[randomI];
                int  numberOfLinkValues = multipleValuesPerDocument ? 2 + Random.Next(10) : 1;
                docs[i] = new RandomDoc(id, numberOfLinkValues, value, from);
                for (int j = 0; j < numberOfLinkValues; j++)
                {
                    string linkValue = context.RandomUniqueValues[Random.Next(context.RandomUniqueValues.Length)];
                    docs[i].LinkValues.Add(linkValue);
                    if (from)
                    {
                        if (!context.FromDocuments.TryGetValue(linkValue, out IList <RandomDoc> fromDocs))
                        {
                            context.FromDocuments[linkValue] = fromDocs = new List <RandomDoc>();
                        }
                        if (!context.RandomValueFromDocs.TryGetValue(value, out IList <RandomDoc> randomValueFromDocs))
                        {
                            context.RandomValueFromDocs[value] = randomValueFromDocs = new List <RandomDoc>();
                        }

                        fromDocs.Add(docs[i]);
                        randomValueFromDocs.Add(docs[i]);
                        document.Add(NewTextField(Random, "from", linkValue, Field.Store.NO));
                    }
                    else
                    {
                        if (!context.ToDocuments.TryGetValue(linkValue, out IList <RandomDoc> toDocuments))
                        {
                            context.ToDocuments[linkValue] = toDocuments = new List <RandomDoc>();
                        }
                        if (!context.RandomValueToDocs.TryGetValue(value, out IList <RandomDoc> randomValueToDocs))
                        {
                            context.RandomValueToDocs[value] = randomValueToDocs = new List <RandomDoc>();
                        }

                        toDocuments.Add(docs[i]);
                        randomValueToDocs.Add(docs[i]);
                        document.Add(NewTextField(Random, "to", linkValue, Field.Store.NO));
                    }
                }

                RandomIndexWriter w;
                if (from)
                {
                    w = fromWriter;
                }
                else
                {
                    w = toWriter;
                }

                w.AddDocument(document);
                if (Random.Next(10) == 4)
                {
                    w.Commit();
                }
                if (VERBOSE)
                {
                    Console.WriteLine("Added document[" + docs[i].Id + "]: " + document);
                }
            }

            // Pre-compute all possible hits for all unique random values. On top of this also compute all possible score for
            // any ScoreMode.
            IndexSearcher fromSearcher = NewSearcher(fromWriter.GetReader());
            IndexSearcher toSearcher   = NewSearcher(toWriter.GetReader());

            for (int i = 0; i < context.RandomUniqueValues.Length; i++)
            {
                string uniqueRandomValue = context.RandomUniqueValues[i];
                string fromField;
                string toField;
                IDictionary <string, IDictionary <int, JoinScore> > queryVals;
                if (context.RandomFrom[i])
                {
                    fromField = "from";
                    toField   = "to";
                    queryVals = context.FromHitsToJoinScore;
                }
                else
                {
                    fromField = "to";
                    toField   = "from";
                    queryVals = context.ToHitsToJoinScore;
                }
                IDictionary <BytesRef, JoinScore> joinValueToJoinScores = new Dictionary <BytesRef, JoinScore>();
                if (multipleValuesPerDocument)
                {
                    fromSearcher.Search(new TermQuery(new Term("value", uniqueRandomValue)),
                                        new CollectorAnonymousInnerClassHelper3(this, context, fromField, joinValueToJoinScores));
                }
                else
                {
                    fromSearcher.Search(new TermQuery(new Term("value", uniqueRandomValue)),
                                        new CollectorAnonymousInnerClassHelper4(this, context, fromField, joinValueToJoinScores));
                }

                IDictionary <int, JoinScore> docToJoinScore = new Dictionary <int, JoinScore>();
                if (multipleValuesPerDocument)
                {
                    if (scoreDocsInOrder)
                    {
                        AtomicReader slowCompositeReader = SlowCompositeReaderWrapper.Wrap(toSearcher.IndexReader);
                        Terms        terms = slowCompositeReader.GetTerms(toField);
                        if (terms != null)
                        {
                            DocsEnum  docsEnum  = null;
                            TermsEnum termsEnum = null;
                            JCG.SortedSet <BytesRef> joinValues =
                                new JCG.SortedSet <BytesRef>(BytesRef.UTF8SortedAsUnicodeComparer);
                            joinValues.UnionWith(joinValueToJoinScores.Keys);
                            foreach (BytesRef joinValue in joinValues)
                            {
                                termsEnum = terms.GetIterator(termsEnum);
                                if (termsEnum.SeekExact(joinValue))
                                {
                                    docsEnum = termsEnum.Docs(slowCompositeReader.LiveDocs, docsEnum, DocsFlags.NONE);
                                    JoinScore joinScore = joinValueToJoinScores[joinValue];

                                    for (int doc = docsEnum.NextDoc();
                                         doc != DocIdSetIterator.NO_MORE_DOCS;
                                         doc = docsEnum.NextDoc())
                                    {
                                        // First encountered join value determines the score.
                                        // Something to keep in mind for many-to-many relations.
                                        if (!docToJoinScore.ContainsKey(doc))
                                        {
                                            docToJoinScore[doc] = joinScore;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        toSearcher.Search(new MatchAllDocsQuery(),
                                          new CollectorAnonymousInnerClassHelper5(this, context, toField, joinValueToJoinScores,
                                                                                  docToJoinScore));
                    }
                }
                else
                {
                    toSearcher.Search(new MatchAllDocsQuery(),
                                      new CollectorAnonymousInnerClassHelper6(this, toField, joinValueToJoinScores,
                                                                              docToJoinScore));
                }
                queryVals[uniqueRandomValue] = docToJoinScore;
            }

            fromSearcher.IndexReader.Dispose();
            toSearcher.IndexReader.Dispose();

            return(context);
        }
Example #42
0
        private void Imprimir_Reporte_Click(object sender, EventArgs e)
        {
            Paragraph paragraph      = new Paragraph(); //se crea el parrafo
            Paragraph paragraphfecha = new Paragraph();

            paragraph.Clear();//limpiar el parrago para agregar mas texto
            iTextSharp.text.Font text = new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 11);
            if (Grid_Obras.RowCount == 0)
            {
                MessageBox.Show("No Hay Datos Para Realizar Un Reporte");
            }
            else
            {
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*";
                if (save.ShowDialog() == DialogResult.OK)
                {
                    Document   doc      = new Document(PageSize.A2.Rotate(), 1, 1, 1, 1);
                    string     filename = save.FileName;
                    FileStream file     = new FileStream(filename, FileMode.OpenOrCreate);
                    PdfWriter  writer   = PdfWriter.GetInstance(doc, file);
                    writer.ViewerPreferences = PdfWriter.PageModeUseThumbs;
                    writer.ViewerPreferences = PdfWriter.PageLayoutOneColumn;
                    doc.Open();
                    paragraph.Font      = new iTextSharp.text.Font(FontFactory.GetFont("Arial", 22, BaseColor.BLACK));
                    paragraph.Alignment = Element.ALIGN_CENTER;
                    paragraph.Add("REPORTE DE OBRAS"); //agregar texto
                    doc.Add(paragraph);                //lo metes al documento
                    paragraph.Clear();
                    doc.Add(Chunk.NEWLINE);
                    paragraphfecha.Alignment = Element.ALIGN_RIGHT;
                    paragraphfecha.Add(DateTime.Now.ToString("dd/MM/yyyy"));
                    doc.Add(paragraphfecha);//lo metes al documento
                    paragraphfecha.Clear();
                    doc.Add(Chunk.NEWLINE);
                    PdfPTable pdftable = new PdfPTable(Grid_Obras.ColumnCount - 0);

                    for (int j = 0; j < Grid_Obras.Columns.Count - 0; j++)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(Grid_Obras.Columns[j].HeaderText, text));
                        cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                        pdftable.AddCell(cell);
                    }

                    pdftable.HeaderRows = 0;
                    for (int i = 0; i < Grid_Obras.Rows.Count; i++)

                    {
                        for (int k = 0; k < Grid_Obras.Columns.Count - 0; k++)
                        {
                            if (Grid_Obras[k, i].Value != null)
                            {
                                pdftable.AddCell(new Phrase(Grid_Obras.Rows[i].Cells[k].Value.ToString(), text));
                                //pdftable.AddCell(new Phrase(dgvLoadAll[k, i].Value.ToString(), text));
                            }
                        }
                    }

                    //float[] widths = new float[] { 15f, 50f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f };

                    // pdftable.SetWidths(widths);
                    doc.Add(pdftable);
                    doc.Close();
                    System.Diagnostics.Process.Start(filename);
                }
            }
        }
        public virtual void TestEmptyIndexWithVectors()
        {
            Directory rd1 = NewDirectory();
            {
                if (VERBOSE)
                {
                    Console.WriteLine("\nTEST: make 1st writer");
                }
                IndexWriter iw      = new IndexWriter(rd1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
                Document    doc     = new Document();
                Field       idField = NewTextField("id", "", Field.Store.NO);
                doc.Add(idField);
                FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
                customType.StoreTermVectors = true;
                doc.Add(NewField("test", "", customType));
                idField.StringValue = "1";
                iw.AddDocument(doc);
                doc.Add(NewTextField("test", "", Field.Store.NO));
                idField.StringValue = "2";
                iw.AddDocument(doc);
                iw.Dispose();

                IndexWriterConfig dontMergeConfig = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))).SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
                if (VERBOSE)
                {
                    Console.WriteLine("\nTEST: make 2nd writer");
                }
                IndexWriter writer = new IndexWriter(rd1, dontMergeConfig);

                writer.DeleteDocuments(new Term("id", "1"));
                writer.Dispose();
                IndexReader ir = DirectoryReader.Open(rd1);
                Assert.AreEqual(2, ir.MaxDoc);
                Assert.AreEqual(1, ir.NumDocs);
                ir.Dispose();

                iw = new IndexWriter(rd1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND));
                iw.ForceMerge(1);
                iw.Dispose();
            }

            Directory rd2 = NewDirectory();
            {
                IndexWriter iw  = new IndexWriter(rd2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
                Document    doc = new Document();
                iw.AddDocument(doc);
                iw.Dispose();
            }

            Directory rdOut = NewDirectory();

            IndexWriter          iwOut = new IndexWriter(rdOut, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
            DirectoryReader      reader1, reader2;
            ParallelAtomicReader pr = new ParallelAtomicReader(SlowCompositeReaderWrapper.Wrap(reader1 = DirectoryReader.Open(rd1)), SlowCompositeReaderWrapper.Wrap(reader2 = DirectoryReader.Open(rd2)));

            // When unpatched, Lucene crashes here with an ArrayIndexOutOfBoundsException (caused by TermVectorsWriter)
            iwOut.AddIndexes(pr);

            // ParallelReader closes any IndexReader you added to it:
            pr.Dispose();

            // assert subreaders were closed
            Assert.AreEqual(0, reader1.RefCount);
            Assert.AreEqual(0, reader2.RefCount);

            rd1.Dispose();
            rd2.Dispose();

            iwOut.ForceMerge(1);
            iwOut.Dispose();

            rdOut.Dispose();
        }
Example #44
0
        public ActionResult buildPDF(List <InformeResponse> lista, string nombreAsada)
        {
            MemoryStream ms = new MemoryStream();
            PdfWriter    pw = new PdfWriter(ms);

            PdfDocument pdfDocument = new PdfDocument(pw);
            Document    doc         = new Document(pdfDocument, PageSize.LETTER, false);

            doc.Add(new Paragraph("Reporte " + nombreAsada).SetFontSize(20).SetTextAlignment(TextAlignment.CENTER).SetFontColor(new DeviceRgb(4, 124, 188)));
            foreach (InformeResponse item in lista)
            {
                Preguntas preguntasObj = TipoFormulario(item.tipo);

                doc.Add(new Paragraph(item.acueducto).SetFontSize(15).SetBold());
                doc.Add(new Paragraph("Fecha: " + item.fecha).SetFontSize(12));
                doc.Add(new Paragraph("Encargado: " + item.encargado).SetFontSize(12).SetPaddingBottom(2));
                doc.Add(new Paragraph("Respuestas ").SetFontSize(12).SetUnderline());

                var infra = JsonConvert.DeserializeObject <Dictionary <string, string> >(item.infraestructura);
                foreach (var kv in infra)
                {
                    if (kv.Key == "P1")
                    {
                        doc.Add(new Paragraph(preguntasObj.p1 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P2")
                    {
                        doc.Add(new Paragraph(preguntasObj.p2 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P3")
                    {
                        doc.Add(new Paragraph(preguntasObj.p3 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P4")
                    {
                        doc.Add(new Paragraph(preguntasObj.p4 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P5")
                    {
                        doc.Add(new Paragraph(preguntasObj.p5 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P6")
                    {
                        doc.Add(new Paragraph(preguntasObj.p6 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P7")
                    {
                        doc.Add(new Paragraph(preguntasObj.p7 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P8")
                    {
                        doc.Add(new Paragraph(preguntasObj.p8 + ": " + kv.Value).SetFontSize(10));
                    }
                    else if (kv.Key == "P9")
                    {
                        doc.Add(new Paragraph(preguntasObj.p9 + ": " + kv.Value).SetFontSize(10));
                    }
                }
                doc.Add(new Paragraph("Comentarios: " + item.comentarios).SetFontSize(12));
                doc.Add(new Paragraph("Tipo de formulario: " + preguntasObj.tipo).SetFontSize(12));
                Cell cell = new Cell();
                cell.Add(new Paragraph("Riesgo " + item.riesgo).SetBorder(new SolidBorder(colorRiesgo(item.riesgo), 1)).SetBackgroundColor(colorRiesgo(item.riesgo)).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER).SetFontSize(14).SetBold());
                doc.Add(cell);

                WebClient webClient = new WebClient();
                byte[]    data      = webClient.DownloadData(item.imagen);

                ImageData imageData = ImageDataFactory.Create(data);
                Image     image     = new Image(imageData);
                var       s         = 0.4;
                float     fwi       = (float)s;
                float     fhei      = (float)s;
                doc.Add(image.Scale(fwi, fhei).SetHorizontalAlignment(HorizontalAlignment.CENTER).SetMarginBottom(15).SetMarginTop(15));
            }
            //imagen del logo de sersa
            var       s2         = 0.08;
            float     fwi2       = (float)s2;
            float     fhei2      = (float)s2;
            WebClient webClient2 = new WebClient();

            byte[]    data2      = webClient2.DownloadData(logoletra);
            ImageData imageData2 = ImageDataFactory.Create(data2);
            Image     image2     = new Image(imageData2);
            Paragraph header     = new Paragraph("");

            header.Add(image2.Scale(fwi2, fhei2).SetMarginBottom(15));


            //imagen del logo de TEC
            var       s3         = 0.4;
            float     fwi3       = (float)s3;
            float     fhei3      = (float)s3;
            WebClient webClient3 = new WebClient();

            byte[]    data3      = webClient3.DownloadData(logotec);
            ImageData imageData3 = ImageDataFactory.Create(data3);
            Image     image3     = new Image(imageData3);
            Paragraph header2    = new Paragraph("");

            header2.Add(image3.Scale(fwi3, fhei3)).SetMarginBottom(10);



            for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++)
            {
                Rectangle pageSize = pdfDocument.GetPage(i).GetPageSize();
                float     x1       = 20;
                float     y1       = pageSize.GetTop() - 55;
                float     x2       = pageSize.GetRight() - 30;
                float     y2       = pageSize.GetTop() - 40;
                doc.ShowTextAligned(header, x1, y1, i, TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
                doc.ShowTextAligned(header2, x2, y2, i, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
            }



            doc.Close();

            byte[] bytesStream = ms.ToArray();
            ms = new MemoryStream();
            ms.Write(bytesStream, 0, bytesStream.Length);
            ms.Position = 0;

            return(new FileStreamResult(ms, "application/pdf"));
        }
Example #45
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            dt = Util.Now;

            doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64);
            var w = PdfWriter.GetInstance(doc, Response.OutputStream);

            var i = (from m in DbUtil.Db.Meetings
                     where m.MeetingId == mtgid
                     select new
            {
                m.Organization.OrganizationName,
                m.Organization.LeaderName,
                m.MeetingDate
            }).SingleOrDefault();

            w.PageEvent = new HeadFoot
            {
                HeaderText = "Guests/Absents Report: {0} - {1} {2:g}".Fmt(
                    i.OrganizationName, i.LeaderName, i.MeetingDate),
                FooterText = "Guests/Absents Report"
            };
            doc.Open();

            var q = VisitsAbsents(mtgid.Value);

            if (!mtgid.HasValue || i == null || q.Count() == 0)
            {
                doc.Add(new Paragraph("no data"));
            }
            else
            {
                var mt = new PdfPTable(1);
                mt.SetNoPadding();
                mt.HeaderRows = 1;

                float[] widths = new float[] { 4f, 6f, 7f, 2.6f, 2f, 3f };
                var     t      = new PdfPTable(widths);
                t.DefaultCell.Border            = PdfPCell.NO_BORDER;
                t.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_TOP;
                t.DefaultCell.SetLeading(2.0f, 1f);
                t.WidthPercentage = 100;

                t.AddHeader("Name", boldfont);
                t.AddHeader("Address", boldfont);
                t.AddHeader("Phone/Email", boldfont);
                t.AddHeader("Last Att.", boldfont);
                t.AddHeader("Birthday", boldfont);
                t.AddHeader("Guest/Member", boldfont);
                mt.AddCell(t);

                var  color = BaseColor.BLACK;
                bool?v     = null;
                foreach (var p in q)
                {
                    if (color == BaseColor.WHITE)
                    {
                        color = new GrayColor(240);
                    }
                    else
                    {
                        color = BaseColor.WHITE;
                    }

                    t = new PdfPTable(widths);
                    t.SetNoBorder();
                    t.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
                    t.DefaultCell.BackgroundColor   = color;

                    if (v != p.visitor)
                    {
                        t.Add("             ------ {0} ------".Fmt(p.visitor == true ? "Guests" : "Absentees"), 6, bigboldfont);
                    }
                    v = p.visitor;

                    t.Add(p.Name, font);

                    var ph = new Paragraph();
                    ph.AddLine(p.Address, font);
                    ph.AddLine(p.Address2, font);
                    ph.AddLine(p.CSZ, font);
                    t.AddCell(ph);

                    ph = new Paragraph();
                    ph.AddLine(p.HomePhone.FmtFone("H"), font);
                    ph.AddLine(p.CellPhone.FmtFone("C"), font);
                    ph.AddLine(p.Email, font);
                    t.AddCell(ph);

                    t.Add(p.LastAttend.FormatDate(), font);
                    t.Add(p.Birthday, font);
                    t.Add(p.Status, font);
                    t.CompleteRow();

                    if (!p.Status.StartsWith("Visit"))
                    {
                        t.Add("", font);
                        t.Add("{0}           {1:n1}{2}"
                              .Fmt(p.AttendStr, p.AttendPct, p.AttendPct.HasValue ? "%" : ""), 5, monofont);
                    }

                    mt.AddCell(t);
                }
                doc.Add(mt);
            }
            doc.Close();
        }
Example #46
0
        /// <summary>
        /// 转换成pdf
        /// </summary>
        /// <param name="model"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string ObjectToPdf(ComparisonQuotaValue model, string filePath)
        {
            string currentDate = DateTime.Now.ToString("yyyyMMdd");
            var    uploadPath  = filePath + $"/" + currentDate + "/";//>>>相当于HttpContext.Current.Server.MapPath("")

            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            //输出的文件名称
            var    _temp    = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            string fileName = string.Format("{0}.pdf", $"{model.QuotaName}_" + _temp, Encoding.UTF8);
            //string newFileName = string.Format("{0}_1.pdf", $"{obj.QuotaName}_" + _temp, Encoding.UTF8);
            string pdfPath     = uploadPath + "\\" + fileName;//自定义生成的pdf名
            string newFilePath = "";

            try
            {
                #region 定义字体样式

                BaseFont bfChinese        = BaseFont.CreateFont($"C://WINDOWS//fonts//simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font     fontChinese_12   = new Font(bfChinese, 18, Font.BOLD, new BaseColor(0, 0, 0));
                Font     fontChinese_11   = new Font(bfChinese, 14, Font.BOLD, new BaseColor(0, 0, 0));
                Font     fontChinese_10   = new Font(bfChinese, 10, Font.NORMAL, new BaseColor(248, 248, 255));
                Font     fontChinese_bold = new Font(bfChinese, 8, Font.BOLD, new BaseColor(0, 0, 0));
                Font     fontChinese_8    = new Font(bfChinese, 8, Font.NORMAL, new BaseColor(0, 0, 0));
                Font     fontChinese      = new Font(bfChinese, 7, Font.NORMAL, new BaseColor(0, 0, 0));
                //黑体
                BaseFont bf_ht = BaseFont.CreateFont("C://WINDOWS//Fonts//simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font     ht_7  = new Font(bf_ht, 7, Font.NORMAL, new BaseColor(0, 0, 0));

                #endregion 定义字体样式

                //行高
                float cellHeight = 20;
                //初始化一个目标文档类
                Document document = new Document(PageSize.A4, 5f, 5f, 30f, 0f);
                //调用PDF的写入方法流
                //注意FileMode-Create表示如果目标文件不存在,则创建,如果已存在,则覆盖。
                PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));

                // 页眉页脚
                string space1 = " ".PadLeft(19, ' ');
                string space2 = " ".PadLeft(120, ' ');

                Chunk  chunk1 = new Chunk(space1 + "中国XX企业对标提升数据报表\r\n\r\n", fontChinese_12);                                      //页眉主题
                Chunk  chunk2 = new Chunk(space2 + "日期: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\r\n", fontChinese_8); //导出时间
                Phrase ph     = new Phrase(9)
                {
                    chunk1,
                    chunk2
                };
                HeaderFooter header = new HeaderFooter(ph, false)
                {
                    Border = Rectangle.NO_BORDER
                };
                document.Header = header;
                //页码
                HeaderFooter footer = new HeaderFooter(new Phrase(4, "页码: ", fontChinese_8), true)
                {
                    Border    = Rectangle.NO_BORDER,
                    Alignment = Element.ALIGN_CENTER,
                    Bottom    = 20
                };
                document.Footer = footer;

                //打开目标文档对象
                document.Open();
                // 创建第一页(如果只有一页的话,这一步可以省略)
                document.NewPage();

                PdfPTable table = new PdfPTable(1)
                {
                    TotalWidth  = 550,
                    LockedWidth = true
                };

                table.SetWidths(new int[] { 550 });
                PdfPCell cell;
                //自定义title
                cell = new PdfPCell(new Phrase($"{model.QuotaName}({model.Stage})", fontChinese_11))
                {
                    Colspan             = 1,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE,
                    Border      = Rectangle.NO_BORDER,
                    FixedHeight = 50
                };
                table.AddCell(cell);
                document.Add(table);

                //自定义创建第一行表头
                table = new PdfPTable(model.Attributes.Count + 2)
                {
                    TotalWidth  = 550,
                    LockedWidth = true
                };

                cell = new PdfPCell(new Phrase("单位名称", fontChinese_10))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE,
                    BackgroundColor     = BaseColor.DarkGray,
                    FixedHeight         = cellHeight
                };
                table.AddCell(cell);

                cell = new PdfPCell(new Phrase("排名", fontChinese_10))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE,
                    BackgroundColor     = BaseColor.DarkGray,
                    FixedHeight         = cellHeight
                };
                table.AddCell(cell);

                model.Attributes.ForEach(x =>
                {
                    cell = new PdfPCell(new Phrase(x.AttributeName, fontChinese_10))
                    {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        BackgroundColor     = BaseColor.DarkGray,
                        FixedHeight         = cellHeight
                    };
                    table.AddCell(cell);
                });

                //数据渲染
                model.EnterpriseComparisonQuotaValue.ForEach(x =>
                {
                    cell = new PdfPCell(new Phrase(x.OrgName, fontChinese_8))
                    {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        FixedHeight         = cellHeight
                    };
                    table.AddCell(cell);

                    cell = new PdfPCell(new Phrase(x.Rank, fontChinese_8))
                    {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        FixedHeight         = cellHeight
                    };
                    table.AddCell(cell);
                    x.Values.ToList().ForEach(m =>
                    {
                        cell = new PdfPCell(new Phrase(m.Value.ToString(), fontChinese_8))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER,
                            VerticalAlignment   = Element.ALIGN_MIDDLE,
                            FixedHeight         = cellHeight
                        };
                        table.AddCell(cell);
                    });
                });

                document.Add(table);
                //关闭目标文件
                document.Close();
                //关闭写入流
                pdfWriter.Close();

                //添加水印
                AddWatermark(pdfPath, "机密文件,请勿泄露", out newFilePath);
            }
            catch (Exception)
            {
                throw;
            }

            return(newFilePath);
        }
Example #47
0
        public void TestInsideBooleanQuery()
        {
            const string idField = "id";
            const string toField = "productId";

            Directory         dir = NewDirectory();
            RandomIndexWriter w   = new RandomIndexWriter(Random, dir,
                                                          NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))
                                                          .SetMergePolicy(NewLogMergePolicy()));

            // 0
            Document doc = new Document();

            doc.Add(new TextField("description", "random text", Field.Store.NO));
            doc.Add(new TextField("name", "name1", Field.Store.NO));
            doc.Add(new TextField(idField, "7", Field.Store.NO));
            w.AddDocument(doc);

            // 1
            doc = new Document();
            doc.Add(new TextField("price", "10.0", Field.Store.NO));
            doc.Add(new TextField(idField, "2", Field.Store.NO));
            doc.Add(new TextField(toField, "7", Field.Store.NO));
            w.AddDocument(doc);

            // 2
            doc = new Document();
            doc.Add(new TextField("price", "20.0", Field.Store.NO));
            doc.Add(new TextField(idField, "3", Field.Store.NO));
            doc.Add(new TextField(toField, "7", Field.Store.NO));
            w.AddDocument(doc);

            // 3
            doc = new Document();
            doc.Add(new TextField("description", "more random text", Field.Store.NO));
            doc.Add(new TextField("name", "name2", Field.Store.NO));
            doc.Add(new TextField(idField, "0", Field.Store.NO));
            w.AddDocument(doc);
            w.Commit();

            // 4
            doc = new Document();
            doc.Add(new TextField("price", "10.0", Field.Store.NO));
            doc.Add(new TextField(idField, "5", Field.Store.NO));
            doc.Add(new TextField(toField, "0", Field.Store.NO));
            w.AddDocument(doc);

            // 5
            doc = new Document();
            doc.Add(new TextField("price", "20.0", Field.Store.NO));
            doc.Add(new TextField(idField, "6", Field.Store.NO));
            doc.Add(new TextField(toField, "0", Field.Store.NO));
            w.AddDocument(doc);

            w.ForceMerge(1);

            IndexSearcher indexSearcher = new IndexSearcher(w.GetReader());

            w.Dispose();

            // Search for product
            Query joinQuery = JoinUtil.CreateJoinQuery(idField, false, toField,
                                                       new TermQuery(new Term("description", "random")), indexSearcher, ScoreMode.Avg);

            BooleanQuery bq = new BooleanQuery();

            bq.Add(joinQuery, Occur.SHOULD);
            bq.Add(new TermQuery(new Term("id", "3")), Occur.SHOULD);

            indexSearcher.Search(bq, new CollectorAnonymousInnerClassHelper(this));

            indexSearcher.IndexReader.Dispose();
            dir.Dispose();
        }
Example #48
0
            public override void Run()
            {
                try
                {
                    IDictionary <string, int?> values = new Dictionary <string, int?>();
                    IList <string>             allIDs = new SynchronizedCollection <string>();

                    StartingGun.Wait();
                    for (int iter = 0; iter < Iters; iter++)
                    {
                        // Add/update a document
                        Document doc = new Document();
                        // Threads must not update the same id at the
                        // same time:
                        if (ThreadRandom.NextDouble() <= AddChance)
                        {
                            string id    = string.Format(CultureInfo.InvariantCulture, "{0}_{1:X4}", ThreadID, ThreadRandom.Next(IdCount));
                            int    field = ThreadRandom.Next(int.MaxValue);
                            doc.Add(new StringField("id", id, Field.Store.YES));
                            doc.Add(new IntField("field", (int)field, Field.Store.YES));
                            w.UpdateDocument(new Term("id", id), doc);
                            Rt.Add(id, field);
                            if (!values.ContainsKey(id))//Key didn't exist before
                            {
                                allIDs.Add(id);
                            }
                            values[id] = field;
                        }

                        if (allIDs.Count > 0 && ThreadRandom.NextDouble() <= DeleteChance)
                        {
                            string randomID = allIDs[ThreadRandom.Next(allIDs.Count)];
                            w.DeleteDocuments(new Term("id", randomID));
                            Rt.Delete(randomID);
                            values[randomID] = Missing;
                        }

                        if (ThreadRandom.NextDouble() <= ReopenChance || Rt.Size() > 10000)
                        {
                            //System.out.println("refresh @ " + rt.Size());
                            Mgr.MaybeRefresh();
                            if (VERBOSE)
                            {
                                IndexSearcher s = Mgr.Acquire();
                                try
                                {
                                    Console.WriteLine("TEST: reopen " + s);
                                }
                                finally
                                {
                                    Mgr.Release(s);
                                }
                                Console.WriteLine("TEST: " + values.Count + " values");
                            }
                        }

                        if (ThreadRandom.Next(10) == 7)
                        {
                            Assert.AreEqual(null, Rt.Get("foo"));
                        }

                        if (allIDs.Count > 0)
                        {
                            string randomID = allIDs[ThreadRandom.Next(allIDs.Count)];
                            int?   expected = values[randomID];
                            if (expected == Missing)
                            {
                                expected = null;
                            }
                            Assert.AreEqual(expected, Rt.Get(randomID), "id=" + randomID);
                        }
                    }
                }
                catch (Exception t)
                {
                    throw new Exception(t.Message, t);
                }
            }
Example #49
0
        public JsonResult CreateSaleReport()
        {
            try {
                var dateFrom = DateTime.Parse(Request.Cookies["dateFrom"]);
                var dateTo   = DateTime.Parse(Request.Cookies["dateTo"]);
                var sales    = new List <Sale>(dbContext.Sale
                                               .Include(pass => pass.PassengerNavigation)
                                               .Include(user => user.PassengerNavigation.UserNavigation)
                                               .Include(ticket => ticket.TicketNavigation)
                                               .Include(departure => departure.TicketNavigation.TrainDepartureTownNavigation)
                                               .Include(arrival => arrival.TicketNavigation.TrainArrivalTownNavigation)
                                               .Where(x => x.SaleDate >= dateFrom && x.SaleDate <= dateTo))
                               .ToList();
                var dest = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + $"/Отчёт по продажам от {dateFrom:yyyy-MM-dd}.pdf";
                var file = new FileInfo(dest);
                file.Directory.Create();
                var pdf      = new PdfDocument(new PdfWriter(dest));
                var document = new Document(pdf, PageSize.A4.Rotate());
                var font     = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);

                float[] columnWidths = { 1, 5, 5, 5 };
                var     table        = new Table(UnitValue.CreatePercentArray(columnWidths));

                var cell = new Cell(1, 4)
                           .Add(new Paragraph($"Отчёт по продажам {dateFrom:yyyy-MM-dd} - {dateTo:yyyy-MM-dd}"))
                           .SetFont(font)
                           .SetFontSize(13)
                           .SetFontColor(DeviceGray.WHITE)
                           .SetBackgroundColor(DeviceGray.BLACK)
                           .SetTextAlignment(TextAlignment.CENTER);
                table.AddHeaderCell(cell);

                Cell[] headerFooter =
                {
                    new Cell().SetFont(font).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("#")),
                    new Cell().SetFont(font).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Номер билета")),
                    new Cell().SetFont(font).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Дата продажи")),
                    new Cell().SetFont(font).SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Цена"))
                };

                foreach (var hfCell in headerFooter)
                {
                    table.AddHeaderCell(hfCell);
                }

                for (int i = 0; i < sales.Count; i++)
                {
                    table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph((i + 1).ToString())));
                    table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(sales[i].IdTicket.ToString())));
                    table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(sales[i].SaleDate.ToString("g"))));
                    table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph(sales[i].TotalPrice.ToString(CultureInfo.InvariantCulture))));
                    if (i == sales.Count - 1)
                    {
                        table.AddCell(new Cell());
                        table.AddCell(new Cell());
                        table.AddCell(new Cell().SetBold().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph("Итог:")));
                        table.AddCell(new Cell().SetTextAlignment(TextAlignment.CENTER).SetFont(font).Add(new Paragraph($"{sales.Sum(x => x.TotalPrice)}")));
                    }
                }
                document.Add(table);
                var process = new Process {
                    StartInfo = new ProcessStartInfo(dest)
                    {
                        UseShellExecute = true
                    }
                };
                process.Start();
                document.Close();
            } catch {
                return(new JsonResult("Не удалось сохранить отчёт"));
            }
            return(new JsonResult("Отчёт сохранен"));
        }
Example #50
0
        private void btnPdf_Click(object sender, EventArgs e)
        {
            try
            {
                using (SaveFileDialog sfd = new SaveFileDialog()
                {
                    Filter = "PDF file|*.pdf", ValidateNames = true
                })
                {
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        using (ManagerContext db = new ManagerContext())
                        {
                            if (dgvSalesList.CurrentRow != null)
                            {
                                int selectedId = (int)dgvSalesList.CurrentRow.Cells[0].Value;
                                if (selectedId > 0)
                                {
                                    string    invoiceNo    = dgvSalesList.CurrentRow.Cells["Invoice"].Value.ToString();
                                    string    i            = "Invoice No: " + invoiceNo;
                                    string    outletName   = dgvSalesList.CurrentRow.Cells["Outlet"].Value.ToString();
                                    string    o            = "Outlet Name: " + outletName;
                                    string    customerName = dgvSalesList.CurrentRow.Cells["Customer"].Value.ToString();
                                    string    c            = "Customer :" + customerName;
                                    string    employeeName = dgvSalesList.CurrentRow.Cells["Employee"].Value.ToString();
                                    string    emp          = "Employee Name: " + employeeName;
                                    string    salesDate    = dgvSalesList.CurrentRow.Cells["Date"].Value.ToString();
                                    string    sDate        = "Sales Date: " + salesDate;
                                    string    total        = dgvSalesList.CurrentRow.Cells["TotalAmount"].Value.ToString();
                                    Document  pdfDocument  = new Document(iTextSharp.text.PageSize.A4, 20, 20, 42, 35);
                                    PdfWriter pdfwriter    = PdfWriter.GetInstance(pdfDocument, new FileStream(sfd.FileName, FileMode.Create));


                                    pdfDocument.Open();
                                    pdfDocument.NewPage();
                                    pdfDocument.AddAuthor("POS");
                                    pdfDocument.AddCreator("LanguageIntegratedDevelopmentTeam");
                                    pdfDocument.AddSubject("SalesReport");
                                    Paragraph heading = new Paragraph("Purchase Details");
                                    heading.Alignment    = Element.ALIGN_CENTER;
                                    heading.SpacingAfter = 18f;
                                    pdfDocument.Add(heading);

                                    Paragraph invoice = new Paragraph(i);
                                    invoice.Alignment    = Element.ALIGN_CENTER;
                                    invoice.SpacingAfter = 18f;
                                    pdfDocument.Add(invoice);

                                    Paragraph outlet = new Paragraph(o);
                                    outlet.Alignment    = Element.ALIGN_CENTER;
                                    outlet.SpacingAfter = 4f;
                                    pdfDocument.Add(outlet);

                                    Paragraph customer = new Paragraph(c);
                                    customer.Alignment    = Element.ALIGN_CENTER;
                                    customer.SpacingAfter = 5F;
                                    pdfDocument.Add(customer);

                                    Paragraph para2 = new Paragraph(emp);
                                    para2.Alignment    = Element.ALIGN_CENTER;
                                    para2.SpacingAfter = 5F;
                                    pdfDocument.Add(para2);
                                    Paragraph para3 = new Paragraph(sDate);
                                    para3.Alignment    = Element.ALIGN_CENTER;
                                    para3.SpacingAfter = 35F;
                                    pdfDocument.Add(para3);


                                    PdfPTable table = new PdfPTable(4);

                                    table.SpacingAfter = 30f;

                                    PdfPCell cell = new PdfPCell(new Phrase("Product Details"));

                                    cell.Colspan             = 4;
                                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                    table.AddCell(cell);
                                    table.AddCell("Name");

                                    table.AddCell("Quantity");

                                    table.AddCell("Cost Price");

                                    table.AddCell("Total Price");


                                    foreach (ListViewItem item in itemListView.Items)
                                    {
                                        foreach (var itm in item.SubItems)
                                        {
                                            table.AddCell(((ListViewItem.ListViewSubItem)itm).Text);
                                        }
                                    }
                                    pdfDocument.Add(table);
                                    pdfDocument.Close();
                                    MessageBox.Show("Your PDF File Has Been Ready....!");
                                }
                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #51
0
 /// <summary>
 /// Adds the property.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 public void AddProperty(string name, object value)
 {
     _document.Add(name, value);
 }
        public void exportGrid(DataGridView dataGrid, string fileName)
        {
            BaseFont baseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
            //Buradan aşağıda başlık bilgisi ekleniyor rapor'a
            PdfPTable pdfTitle = new PdfPTable(1);

            pdfTitle.DefaultCell.BorderWidth         = 0;
            pdfTitle.WidthPercentage                 = 300;
            pdfTitle.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

            Chunk chnkTitle = new Chunk("Kullanici Raporu", FontFactory.GetFont("Times New Roman"));

            chnkTitle.Font.Size = 40;
            pdfTitle.AddCell(new Phrase(chnkTitle));

            //Buradan aşağısında tarihi yazdırıyoruz!
            PdfPTable pdfDateTime = new PdfPTable(1);

            pdfDateTime.DefaultCell.BorderWidth         = 0;
            pdfDateTime.WidthPercentage                 = 100;
            pdfDateTime.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

            string thisDay    = DateTime.Now.ToString("dddd, dd MMMM yyyy");
            Chunk  dateString = new Chunk(thisDay, FontFactory.GetFont("Times New Roman"));

            dateString.Font.Size = 20;
            pdfDateTime.AddCell(new Phrase(dateString));

            //Alt tarafta pdf dosyasına ilgili tabşo yu yazdırıyoruz!
            PdfPTable pdfTable = new PdfPTable(dataGrid.Columns.Count);

            pdfTable.DefaultCell.Padding     = 5;
            pdfTable.WidthPercentage         = 100;
            pdfTable.HorizontalAlignment     = Element.ALIGN_LEFT;
            pdfTable.DefaultCell.BorderWidth = 1;

            iTextSharp.text.Font text = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);

            //Başlık Ekleme
            foreach (DataGridViewColumn column in dataGrid.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
                cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
                pdfTable.AddCell(cell);
            }

            //Satırları Ekleme
            foreach (DataGridViewRow row in dataGrid.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    pdfTable.AddCell(new Phrase(cell.Value.ToString(), text));
                }
            }

            var saveFileDialog = new SaveFileDialog();

            saveFileDialog.FileName   = fileName;
            saveFileDialog.DefaultExt = ".pdf";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                using (FileStream stream = new FileStream(saveFileDialog.FileName, FileMode.Create))
                {
                    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                    PdfWriter.GetInstance(pdfDoc, stream);

                    pdfDoc.Open();
                    pdfDoc.Add(pdfTitle);
                    pdfDoc.Add(pdfDateTime);//Burada pdf dosyasına tarih'i yazdırıyoruz!
                    pdfDoc.Add(pdfTable);
                    pdfDoc.Close();
                    stream.Close();
                }
            }
        }
Example #53
0
        /// <summary>
        /// GroupEntity转换成<see cref="Lucene.Net.Documents.Document"/>
        /// </summary>
        /// <param name="GroupEntity">群组实体</param>
        /// <returns>Lucene.Net.Documents.Document</returns>
        public static Document Convert(GroupEntity group)
        {
            Document doc = new Document();

            //索引群组基本信息
            doc.Add(new Field(GroupIndexDocument.GroupId, group.GroupId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(GroupIndexDocument.GroupName, group.GroupName, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field(GroupIndexDocument.Description, group.Description, Field.Store.NO, Field.Index.ANALYZED));
            doc.Add(new Field(GroupIndexDocument.IsPublic, group.IsPublic == true ? "1" : "0", Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(GroupIndexDocument.AreaCode, group.AreaCode, Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(GroupIndexDocument.UserId, group.UserId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(GroupIndexDocument.AuditStatus, ((int)group.AuditStatus).ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(GroupIndexDocument.DateCreated, DateTools.DateToString(group.DateCreated, DateTools.Resolution.DAY), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(GroupIndexDocument.MemberCount, group.MemberCount.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.Add(new Field(GroupIndexDocument.GrowthValue, group.GrowthValue.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            if (group.Category != null)
            {
                doc.Add(new Field(GroupIndexDocument.CategoryName, group.Category.CategoryName, Field.Store.YES, Field.Index.ANALYZED));
                doc.Add(new Field(GroupIndexDocument.CategoryId, group.Category.CategoryId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            }

            //索引群组tag
            foreach (string tagName in group.TagNames)
            {
                doc.Add(new Field(GroupIndexDocument.Tag, tagName.ToLower(), Field.Store.YES, Field.Index.ANALYZED));
            }

            return(doc);
        }
        public ActionResult PurchaseDetailReport(String StartDate, String EndDate, String CompanyId, String BranchId)
        {
            // ==============================
            // PDF Settings and Customization
            // ==============================
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // =====
            // Fonts
            // =====
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10     = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial12Bold = FontFactory.GetFont("Arial", 12, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.Company).FirstOrDefault();
            var address     = (from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.Address).FirstOrDefault();
            var contactNo   = (from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.ContactNumber).FirstOrDefault();
            var branch      = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.Branch).FirstOrDefault();

            // ===========
            // Header Page
            // ===========
            PdfPTable headerPage = new PdfPTable(2);

            float[] widthsCellsHeaderPage = new float[] { 100f, 75f };
            headerPage.SetWidths(widthsCellsHeaderPage);
            headerPage.WidthPercentage = 100;
            headerPage.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Purchase Detail Report", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Date From " + Convert.ToDateTime(StartDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) + " to " + Convert.ToDateTime(EndDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Printed " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(headerPage);
            document.Add(line);

            // ===========================
            // Data (Purchase Order Items)
            // ===========================
            var purchaseOrderItems = from d in db.TrnPurchaseOrderItems
                                     where d.TrnPurchaseOrder.PODate >= Convert.ToDateTime(StartDate) &&
                                     d.TrnPurchaseOrder.PODate <= Convert.ToDateTime(EndDate) &&
                                     d.TrnPurchaseOrder.MstBranch.CompanyId == Convert.ToInt32(CompanyId) &&
                                     d.TrnPurchaseOrder.BranchId == Convert.ToInt32(BranchId) &&
                                     d.TrnPurchaseOrder.IsLocked == true
                                     select new Models.TrnPurchaseOrderItem
            {
                Id       = d.Id,
                POId     = d.POId,
                Branch   = d.TrnPurchaseOrder.MstBranch.Branch,
                PO       = d.TrnPurchaseOrder.PONumber,
                PODate   = d.TrnPurchaseOrder.PODate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture),
                Supplier = d.TrnPurchaseOrder.MstArticle.Article,
                Item     = d.MstArticle.Article,
                Price    = d.MstArticle.Price,
                Unit     = d.MstUnit.Unit,
                Quantity = d.Quantity,
                Amount   = d.Amount
            };

            if (purchaseOrderItems.Any())
            {
                // ============
                // Branch Title
                // ============
                PdfPTable branchTitle           = new PdfPTable(1);
                float[]   widthCellsBranchTitle = new float[] { 100f };
                branchTitle.SetWidths(widthCellsBranchTitle);
                branchTitle.WidthPercentage = 100;
                PdfPCell branchHeaderColspan = (new PdfPCell(new Phrase(branch, fontArial12Bold))
                {
                    HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 14f, Border = 0
                });
                branchTitle.AddCell(branchHeaderColspan);
                document.Add(branchTitle);

                // ====
                // Data
                // ====
                PdfPTable data            = new PdfPTable(8);
                float[]   widthsCellsData = new float[] { 15f, 13f, 25f, 25f, 15f, 10f, 15f, 15f };
                data.SetWidths(widthsCellsData);
                data.WidthPercentage = 100;
                data.AddCell(new PdfPCell(new Phrase("PO Number", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("PO Date", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Supplier", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Item", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Price", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Unit", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Quantity", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Amount", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });

                Decimal total = 0;
                foreach (var purchaseOrderItem in purchaseOrderItems)
                {
                    data.AddCell(new PdfPCell(new Phrase(purchaseOrderItem.PO, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(purchaseOrderItem.PODate, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(purchaseOrderItem.Supplier, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(purchaseOrderItem.Item, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(purchaseOrderItem.Price.ToString("#,##0.00"), fontArial10))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(purchaseOrderItem.Unit, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(purchaseOrderItem.Quantity.ToString("#,##0.00"), fontArial10))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(purchaseOrderItem.Amount.ToString("#,##0.00"), fontArial10))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    total += purchaseOrderItem.Amount;
                }

                // =====
                // Total
                // =====
                data.AddCell(new PdfPCell(new Phrase("Total", fontArial10Bold))
                {
                    Colspan = 7, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 10f, PaddingLeft = 10f
                });
                data.AddCell(new PdfPCell(new Phrase(total.ToString("#,##0.00"), fontArial10Bold))
                {
                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                });
                document.Add(data);
            }

            // Document End
            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
Example #55
0
        /**
         * Split a given index into 3 indexes for training, test and cross validation tasks respectively
         *
         * @param originalIndex        an {@link AtomicReader} on the source index
         * @param trainingIndex        a {@link Directory} used to write the training index
         * @param testIndex            a {@link Directory} used to write the test index
         * @param crossValidationIndex a {@link Directory} used to write the cross validation index
         * @param analyzer             {@link Analyzer} used to create the new docs
         * @param fieldNames           names of fields that need to be put in the new indexes or <code>null</code> if all should be used
         * @throws IOException if any writing operation fails on any of the indexes
         */
        public void Split(AtomicReader originalIndex, Directory trainingIndex, Directory testIndex, Directory crossValidationIndex, Analyzer analyzer, params string[] fieldNames)
        {
            // create IWs for train / test / cv IDXs
            IndexWriter testWriter     = new IndexWriter(testIndex, new IndexWriterConfig(Util.LuceneVersion.LUCENE_CURRENT, analyzer));
            IndexWriter cvWriter       = new IndexWriter(crossValidationIndex, new IndexWriterConfig(Util.LuceneVersion.LUCENE_CURRENT, analyzer));
            IndexWriter trainingWriter = new IndexWriter(trainingIndex, new IndexWriterConfig(Util.LuceneVersion.LUCENE_CURRENT, analyzer));

            try
            {
                int size = originalIndex.MaxDoc;

                IndexSearcher indexSearcher = new IndexSearcher(originalIndex);
                TopDocs       topDocs       = indexSearcher.Search(new MatchAllDocsQuery(), Int32.MaxValue);

                // set the type to be indexed, stored, with term vectors
                FieldType ft = new FieldType(TextField.TYPE_STORED);
                ft.StoreTermVectors         = true;
                ft.StoreTermVectorOffsets   = true;
                ft.StoreTermVectorPositions = true;

                int b = 0;

                // iterate over existing documents
                foreach (ScoreDoc scoreDoc in topDocs.ScoreDocs)
                {
                    // create a new document for indexing
                    Document doc = new Document();
                    if (fieldNames != null && fieldNames.Length > 0)
                    {
                        foreach (String fieldName in fieldNames)
                        {
                            doc.Add(new Field(fieldName, originalIndex.Document(scoreDoc.Doc).GetField(fieldName).ToString(), ft));
                        }
                    }
                    else
                    {
                        foreach (IndexableField storableField in originalIndex.Document(scoreDoc.Doc).Fields)
                        {
                            if (storableField.ReaderValue != null)
                            {
                                doc.Add(new Field(storableField.Name(), storableField.ReaderValue, ft));
                            }
                            else if (storableField.BinaryValue() != null)
                            {
                                doc.Add(new Field(storableField.Name(), storableField.BinaryValue(), ft));
                            }
                            else if (storableField.StringValue != null)
                            {
                                doc.Add(new Field(storableField.Name(), storableField.StringValue, ft));
                            }
                            else if (storableField.NumericValue != null)
                            {
                                doc.Add(new Field(storableField.Name(), storableField.NumericValue.ToString(), ft));
                            }
                        }
                    }

                    // add it to one of the IDXs
                    if (b % 2 == 0 && testWriter.MaxDoc < size * _testRatio)
                    {
                        testWriter.AddDocument(doc);
                    }
                    else if (cvWriter.MaxDoc < size * _crossValidationRatio)
                    {
                        cvWriter.AddDocument(doc);
                    }
                    else
                    {
                        trainingWriter.AddDocument(doc);
                    }
                    b++;
                }
            }
            catch (Exception e)
            {
                throw new IOException("Exceptio in DatasetSplitter", e);
            }
            finally
            {
                testWriter.Commit();
                cvWriter.Commit();
                trainingWriter.Commit();
                // close IWs
                testWriter.Dispose();
                cvWriter.Dispose();
                trainingWriter.Dispose();
            }
        }
Example #56
0
        private static void CreateIndexContent()
        {
            using (FSDirectory directory = FSDirectory.Open(new DirectoryInfo(m_directoryPath), new NativeFSLockFactory())) //指定索引文件(打开索引目录) FS指的是就是FileSystem
            {
                bool isUpdate = IndexReader.IndexExists(directory);                                                         //IndexReader:对索引进行读取的类。该语句的作用:判断索引库文件夹是否存在以及索引特征文件是否存在。
                if (isUpdate)
                {
                    //同时只能有一段代码对索引库进行写操作。当使用IndexWriter打开directory时会自动对索引库文件上锁。
                    //如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁(提示一下:如果我现在正在写着已经加锁了,但是还没有写完,这时候又来一个请求,那么不就解锁了吗?这个问题后面会解决)
                    if (IndexWriter.IsLocked(directory))
                    {
                        IndexWriter.Unlock(directory);
                    }
                }

                using (IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, IndexWriter.MaxFieldLength.UNLIMITED))                //向索引库中写索引。这时在这里加锁。
                {
                    //如果队列中有数据,获取队列中的数据写到Lucene.Net中。
                    while (Queue.Count > 0)
                    {
                        KeyValuePair <T, LuceneTypeEnum> keyValuePair = Queue.Dequeue();
                        T            model        = keyValuePair.Key;
                        Type         type         = model.GetType();
                        PropertyInfo propertyInfo = type.GetProperty(m_luceneDataModels[0].PropertyName);
                        writer.DeleteDocuments(new Term(m_luceneDataModels[0].FieldName, propertyInfo.GetValue(model).ObjectToString()));                        //删除
                        if (keyValuePair.Value == LuceneTypeEnum.Delete)
                        {
                            continue;
                        }
                        //表示一篇文档。
                        Document document = new Document();
                        //Field.Store.YES:表示是否存储原值。只有当Field.Store.YES在后面才能用doc.Get("number")取出值来.Field.Index. NOT_ANALYZED:不进行分词保存
                        //Field.Index. ANALYZED:进行分词保存:也就是要进行全文的字段要设置分词 保存(因为要进行模糊查询
                        //Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS:不仅保存分词还保存分词的距离。
                        foreach (FieldDataModel item in m_luceneDataModels)
                        {
                            propertyInfo = type.GetProperty(item.PropertyName);
                            var propertyValue = propertyInfo.GetValue(model);
                            if (propertyValue != null)
                            {
                                string     valueString = propertyValue.ToString();
                                IFieldable fieldable   = null;
                                if (item.FieldType == TypeCode.String)
                                {
                                    fieldable = new Field(item.FieldName, propertyInfo.GetValue(model).ObjectToString(), item.Store, item.Index, item.TermVector);
                                }
                                else
                                {
                                    NumericField numericField = new NumericField(item.FieldName, item.Store, item.Index == Field.Index.ANALYZED_NO_NORMS);
                                    switch (item.FieldType)
                                    {
                                    case TypeCode.Double:
                                        numericField.SetDoubleValue(Convert.ToDouble(valueString));
                                        break;

                                    case TypeCode.Single:
                                        numericField.SetFloatValue(Convert.ToSingle(valueString));
                                        break;

                                    case TypeCode.Int32:
                                        numericField.SetIntValue(Convert.ToInt32(valueString));
                                        break;

                                    case TypeCode.Int64:
                                        numericField.SetLongValue(Convert.ToInt64(valueString));
                                        break;

                                    default:
                                        break;
                                    }
                                    fieldable = numericField;
                                }
                                document.Add(fieldable);
                            }
                        }
                        writer.AddDocument(document);
                    }
                }                //会自动解锁。
            }
        }
        public MemoryStream GeneratePdfTemplate(GarmentShippingPaymentDispositionViewModel viewModel, int timeoffset)
        {
            const int MARGIN = 20;

            Font header_font_bold_big        = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12);
            Font header_font_bold            = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10);
            Font header_font_bold_underlined = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12, Font.UNDERLINE);
            Font header_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 11);
            Font normal_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10);
            Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10, Font.UNDERLINE);
            Font normal_font_bold       = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10);

            Document document = new Document(PageSize.A4, MARGIN, MARGIN, 40, MARGIN);

            MemoryStream stream = new MemoryStream();
            PdfWriter    writer = PdfWriter.GetInstance(document, stream);

            document.Open();

            #region header

            Paragraph title = new Paragraph("LAMPIRAN DISPOSISI PEMBAYARAN COURIER\n\n\n", header_font_bold);
            title.Alignment = Element.ALIGN_CENTER;

            Paragraph title1 = new Paragraph("DISPOSISI BIAYA SHIPMENT", normal_font_underlined);
            Paragraph no     = new Paragraph(viewModel.dispositionNo, normal_font);
            Paragraph title2 = new Paragraph("Kepada : \nBp./Ibu Kasir Exp Garment PT Danliris", normal_font);

            Paragraph words = new Paragraph($"\nHarap dibayarkan kepada {viewModel.courier.Name} {viewModel.address} " +
                                            $"NPWP {viewModel.npwp} untuk tagihan Invoice No. {viewModel.invoiceNumber} Tgl. " +
                                            $"{viewModel.invoiceDate.ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("id-ID"))}" +
                                            $" Faktur Pajak No.{viewModel.invoiceTaxNumber} dengan rincian sbb : ", normal_font);

            document.Add(title);
            document.Add(title1);
            document.Add(no);
            document.Add(title2);
            document.Add(words);
            #endregion



            #region bodyTable

            PdfPTable tableBody = new PdfPTable(5);
            tableBody.WidthPercentage = 70;
            tableBody.SetWidths(new float[] { 3f, 0.5f, 1f, 2.8f, 1f });

            PdfPCell cellCenterNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell cellLeftNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellRightNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            PdfPCell cellLeftNoBorder1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellLeftTopBorder = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellRightTopBorder = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };

            var last = viewModel.billDetails.Last();
            foreach (var bill in viewModel.billDetails)
            {
                cellLeftNoBorder.Phrase = new Phrase("- " + bill.billDescription, normal_font);
                tableBody.AddCell(cellLeftNoBorder);
                cellCenterNoBorder.Phrase = new Phrase(":", normal_font);
                tableBody.AddCell(cellCenterNoBorder);
                cellLeftNoBorder.Phrase = new Phrase("RP", normal_font);
                tableBody.AddCell(cellLeftNoBorder);
                cellRightNoBorder.Phrase = new Phrase(string.Format("{0:n2}", bill.amount), normal_font);
                tableBody.AddCell(cellRightNoBorder);
                if (bill == last)
                {
                    cellLeftNoBorder.Phrase = new Phrase("(+)", normal_font);
                    tableBody.AddCell(cellLeftNoBorder);
                }
                else
                {
                    cellLeftNoBorder.Phrase = new Phrase("", normal_font);
                    tableBody.AddCell(cellLeftNoBorder);
                }
            }

            cellLeftNoBorder.Phrase = new Phrase("- Total Amount", normal_font);
            tableBody.AddCell(cellLeftNoBorder);
            cellCenterNoBorder.Phrase = new Phrase(":", normal_font);
            tableBody.AddCell(cellCenterNoBorder);
            cellLeftTopBorder.Phrase = new Phrase("RP", normal_font);
            tableBody.AddCell(cellLeftTopBorder);
            cellRightTopBorder.Phrase = new Phrase(string.Format("{0:n2}", viewModel.billValue), normal_font);
            tableBody.AddCell(cellRightTopBorder);
            cellLeftNoBorder.Phrase = new Phrase("", normal_font_bold);
            tableBody.AddCell(cellLeftNoBorder);

            cellLeftNoBorder.Phrase = new Phrase($"- PPH {viewModel.incomeTax.name} ({viewModel.incomeTax.rate}%)", normal_font_bold);
            tableBody.AddCell(cellLeftNoBorder);
            cellCenterNoBorder.Phrase = new Phrase(":", normal_font_bold);
            tableBody.AddCell(cellCenterNoBorder);
            cellLeftNoBorder.Phrase = new Phrase("RP", normal_font_bold);
            tableBody.AddCell(cellLeftNoBorder);
            cellRightNoBorder.Phrase = new Phrase(string.Format("{0:n2}", viewModel.IncomeTaxValue), normal_font_bold);
            tableBody.AddCell(cellRightNoBorder);
            cellLeftNoBorder.Phrase = new Phrase("(-)", normal_font_bold);
            tableBody.AddCell(cellLeftNoBorder);

            cellLeftNoBorder.Phrase = new Phrase("", normal_font_bold);
            tableBody.AddCell(cellLeftNoBorder);
            cellCenterNoBorder.Phrase = new Phrase("", normal_font_bold);
            tableBody.AddCell(cellCenterNoBorder);
            cellLeftTopBorder.Phrase = new Phrase("RP", normal_font);
            tableBody.AddCell(cellLeftTopBorder);
            cellRightTopBorder.Phrase = new Phrase(string.Format("{0:n2}", viewModel.billValue - viewModel.IncomeTaxValue), normal_font);
            tableBody.AddCell(cellRightTopBorder);
            cellLeftNoBorder.Phrase = new Phrase("", normal_font_bold);
            tableBody.AddCell(cellLeftNoBorder);

            cellLeftNoBorder.Phrase = new Phrase("- PPN", normal_font);
            tableBody.AddCell(cellLeftNoBorder);
            cellCenterNoBorder.Phrase = new Phrase(":", normal_font);
            tableBody.AddCell(cellCenterNoBorder);
            cellLeftNoBorder.Phrase = new Phrase("RP", normal_font);
            tableBody.AddCell(cellLeftNoBorder);
            cellRightNoBorder.Phrase = new Phrase(string.Format("{0:n2}", viewModel.vatValue), normal_font);
            tableBody.AddCell(cellRightNoBorder);
            cellLeftNoBorder.Phrase = new Phrase("(+)", normal_font_bold);
            tableBody.AddCell(cellLeftNoBorder);

            cellLeftNoBorder.Phrase = new Phrase("- Total Bayar", normal_font);
            tableBody.AddCell(cellLeftNoBorder);
            cellCenterNoBorder.Phrase = new Phrase(":", normal_font_bold);
            tableBody.AddCell(cellCenterNoBorder);
            cellLeftTopBorder.Phrase = new Phrase("RP", normal_font_bold);
            tableBody.AddCell(cellLeftTopBorder);
            cellRightTopBorder.Phrase = new Phrase(string.Format("{0:n2}", viewModel.totalBill), normal_font_bold);
            tableBody.AddCell(cellRightTopBorder);
            cellLeftNoBorder.Phrase = new Phrase("", normal_font_bold);
            tableBody.AddCell(cellLeftNoBorder);

            tableBody.SpacingAfter        = 10;
            tableBody.SpacingBefore       = 5;
            tableBody.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(tableBody);

            var terbilang = NumberToTextIDN.terbilang((double)viewModel.totalBill) + " rupiah";

            Paragraph trbilang = new Paragraph($"[ Terbilang : {terbilang} ]\n", normal_font);
            document.Add(trbilang);
            #endregion

            #region bank
            Paragraph units = new Paragraph("\nBeban Per Unit", normal_font_bold);
            document.Add(units);

            PdfPTable tableUnit = new PdfPTable(2);
            tableUnit.WidthPercentage = 50;
            tableUnit.SetWidths(new float[] { 1f, 1f });

            PdfPCell cellCenter = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell cellLeft = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellRight = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };


            cellCenter.Phrase = new Phrase("Unit", normal_font_bold);
            tableUnit.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("Amount", normal_font_bold);
            tableUnit.AddCell(cellCenter);

            foreach (var unitItem in viewModel.unitCharges)
            {
                cellLeft.Phrase = new Phrase(unitItem.unit.Code, normal_font);
                tableUnit.AddCell(cellLeft);
                cellRight.Phrase = new Phrase(string.Format("{0:n2}", unitItem.billAmount), normal_font);
                tableUnit.AddCell(cellRight);
            }

            tableUnit.SpacingAfter        = 10;
            tableUnit.SpacingBefore       = 5;
            tableUnit.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(tableUnit);


            Paragraph closing = new Paragraph("Demikian permohonan kami, terima kasih.\n\n", normal_font);
            document.Add(closing);
            #endregion

            #region sign
            PdfPTable tableSign = new PdfPTable(4);
            tableSign.WidthPercentage = 100;
            tableSign.SetWidths(new float[] { 1f, 1f, 1f, 1f });

            PdfPCell cellBodySignNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };

            cellBodySignNoBorder.Phrase = new Phrase($"Terima kasih, \nSolo, {DateTimeOffset.Now.ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("id-ID"))}", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);


            cellBodySignNoBorder.Phrase = new Phrase("Hormat kami,\n\n\n\n", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("Mengetahui,\n\n\n\n", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("Menyetujui,\n\n\n\n", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("Dicek oleh,\n\n\n\n", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);


            cellBodySignNoBorder.Phrase = new Phrase("(                           )", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("(                           )", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("(                           )", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("(                           )", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);

            document.Add(tableSign);
            #endregion

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
        public virtual void Test()
        {
            Directory         dir      = NewDirectory();
            Analyzer          analyzer = new AnalyzerAnonymousInnerClassHelper(this, Analyzer.PER_FIELD_REUSE_STRATEGY);
            IndexWriterConfig iwc      = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);

            iwc.SetCodec(TestUtil.AlwaysPostingsFormat(new Lucene41PostingsFormat()));
            // TODO we could actually add more fields implemented with different PFs
            // or, just put this test into the usual rotation?
            RandomIndexWriter iw           = new RandomIndexWriter(Random(), dir, (IndexWriterConfig)iwc.Clone());
            Document          doc          = new Document();
            FieldType         docsOnlyType = new FieldType(TextField.TYPE_NOT_STORED);

            // turn this on for a cross-check
            docsOnlyType.StoreTermVectors = true;
            docsOnlyType.IndexOptions     = FieldInfo.IndexOptions.DOCS_ONLY;

            FieldType docsAndFreqsType = new FieldType(TextField.TYPE_NOT_STORED);

            // turn this on for a cross-check
            docsAndFreqsType.StoreTermVectors = true;
            docsAndFreqsType.IndexOptions     = FieldInfo.IndexOptions.DOCS_AND_FREQS;

            FieldType positionsType = new FieldType(TextField.TYPE_NOT_STORED);

            // turn these on for a cross-check
            positionsType.StoreTermVectors         = true;
            positionsType.StoreTermVectorPositions = true;
            positionsType.StoreTermVectorOffsets   = true;
            positionsType.StoreTermVectorPayloads  = true;
            FieldType offsetsType = new FieldType(positionsType);

            offsetsType.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
            Field field1 = new Field("field1docs", "", docsOnlyType);
            Field field2 = new Field("field2freqs", "", docsAndFreqsType);
            Field field3 = new Field("field3positions", "", positionsType);
            Field field4 = new Field("field4offsets", "", offsetsType);
            Field field5 = new Field("field5payloadsFixed", "", positionsType);
            Field field6 = new Field("field6payloadsVariable", "", positionsType);
            Field field7 = new Field("field7payloadsFixedOffsets", "", offsetsType);
            Field field8 = new Field("field8payloadsVariableOffsets", "", offsetsType);

            doc.Add(field1);
            doc.Add(field2);
            doc.Add(field3);
            doc.Add(field4);
            doc.Add(field5);
            doc.Add(field6);
            doc.Add(field7);
            doc.Add(field8);
            for (int i = 0; i < MAXDOC; i++)
            {
                string stringValue = Convert.ToString(i) + " verycommon " + English.IntToEnglish(i).Replace('-', ' ') + " " + TestUtil.RandomSimpleString(Random());
                field1.StringValue = stringValue;
                field2.StringValue = stringValue;
                field3.StringValue = stringValue;
                field4.StringValue = stringValue;
                field5.StringValue = stringValue;
                field6.StringValue = stringValue;
                field7.StringValue = stringValue;
                field8.StringValue = stringValue;
                iw.AddDocument(doc);
            }
            iw.Dispose();
            Verify(dir);
            TestUtil.CheckIndex(dir); // for some extra coverage, checkIndex before we forceMerge
            iwc.SetOpenMode(OpenMode_e.APPEND);
            IndexWriter iw2 = new IndexWriter(dir, (IndexWriterConfig)iwc.Clone());

            iw2.ForceMerge(1);
            iw2.Dispose();
            Verify(dir);
            dir.Dispose();
        }
Example #59
0
        public IHttpActionResult PDFReport(DateForm query)
        {
            if (query.Id == null)
            {
                return(BadRequest());
            }

            List <Trip> listOfTrips = db.Trips
                                      .Where(x => x.Vehicle.Id == query.Id &&
                                             x.DateTime >= query.FirstDate &&
                                             x.DateTime <= query.LastDate).Include(x => x.Vehicle)
                                      .ToList();


            var currentDate    = DateTime.Now;
            var currentVehicle = db.Vehicles.Where(x => x.Id == query.Id).First();



            //New table
            PdfPTable table = new PdfPTable(7);

            table.WidthPercentage = 100;

            table.AddCell("Datum");
            table.AddCell("Mätarställning start");
            table.AddCell("Mätarställning ankomst");
            table.AddCell("Startadress");
            table.AddCell("Ankomstadress");
            table.AddCell("Ärende");
            table.AddCell("Anteckningar");

            if (listOfTrips != null)
            {
                foreach (var item in listOfTrips)
                {
                    table.AddCell(item.DateTime.ToShortDateString());
                    table.AddCell(item.StartMilage.ToString());
                    table.AddCell(item.ArrivalMilage.ToString());
                    table.AddCell(item.StartAddress);
                    table.AddCell(item.ArrivalAddress);
                    table.AddCell(item.Errand);
                    table.AddCell(item.Notes);
                }
            }

            //Test path
            //string filePath = @"F:\Journey\";
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "PDF\\";


            //Generate file name - "Journey_2017-08-07_SAD465.pdf
            string fileName = "Journey_" + currentDate.ToString("yyyyMMddHHmmssfff") + "_" + currentVehicle.RegistrationNumber + ".pdf";


            //If the directory in the filepath doesn't exist make a new one
            Directory.CreateDirectory(Path.GetDirectoryName(filePath));


            FileStream fs  = new FileStream(filePath + fileName, FileMode.Create, FileAccess.Write, FileShare.None);
            Document   doc = new Document();


            PdfWriter writer = PdfWriter.GetInstance(doc, fs);


            doc.Open();

            //Populate pdf with data
            doc.Add(new Paragraph("Rapportdatum: " + currentDate.ToShortDateString()));
            doc.Add(new Paragraph("Fordon: " + currentVehicle.RegistrationNumber));
            doc.Add(new Paragraph("Datumspann: " + query.FirstDate.ToShortDateString() + " - " + query.LastDate.ToShortDateString()));

            Chunk linebreak = new Chunk(new LineSeparator(4f, 100f, BaseColor.BLACK, Element.ALIGN_CENTER, -1));

            doc.Add(linebreak);
            doc.Add(table);
            doc.Close();

            string baseUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);

            return(Ok(baseUrl + "/Pdf/" + fileName));
        }
Example #60
0
 protected internal virtual Document AddId(Document doc, string id)
 {
     doc.Add(new StringField("id", id, Field.Store.NO));
     return(doc);
 }