i need to export data to pdf in specfic format - pdf

i am using this function to export data from database to pdf but its output like table ... i want to export a specfic row in format like :
id :
Name :
Gender :
Salary :
how do i do this ..
thanks in advance
public void ExportToPDF()
{
SqlCommand cmd = new SqlCommand("SELECT EmployeeId , EmployeeName , EmployeeGender , EmployeeSalary , isActive FROM Employee", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView gridview1 = new GridView();
gridview1.AllowPaging = false;
gridview1.DataSource = ds;
gridview1.DataBind();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=DataSet.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridview1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4 , 10f , 10f , 10f , 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc , Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}

Please take a look at the UnitedStates example. For the sake of simplicity, I don't use a database but a CSV file. It should be very easy to adapt the example so that it accepts it data from a database rather than by parsing a CSV.
The key class you need is PdfPTable. For instance, if databaseObject is an object that you created to store the data from your database (e.g. the contents of a record), you need something like this:0
PdfPTable table = new PdfPTable(2);
table.addCell("Id:");
table.addCell(databaseObject.getId());
table.addCell("Name:");
table.addCell(databaseObject.getName());
I see that you are using HTMLWorker in your code. This is problematic for two reasons:
It implies that you first convert all your data to XHTML. This costs processing time and if you don't need XHTML, then that time is wasted.
The HTMLWorker class is obsolete. It is no longer supported. If you do want to convert XHTML tables to PDF, you should use XML Worker as is done in these examples
Obviously, you can solve your problem in many other ways. Watch this video and you'll discover that you could also create a template (see for instance state.pdf) and then fill this form like this:
public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader,
new FileOutputStream(dest));
AcroFields fields = stamper.getAcroFields();
fields.setField("name", "CALIFORNIA");
fields.setField("abbr", "CA");
fields.setField("capital", "Sacramento");
fields.setField("city", "Los Angeles");
fields.setField("population", "36,961,664");
fields.setField("surface", "163,707");
fields.setField("timezone1", "PT (UTC-8)");
fields.setField("timezone2", "-");
fields.setField("dst", "YES");
stamper.close();
reader.close();
}
That is shown in the FillForm example.
It's a pity that, with the abundance of documentation that can be found online (of which I only use a handful of examples), you chose a code snippet that doesn't come close to doing what you wanted to do.

Related

How to check whether table column of the binary type has a value?

The Download command is showing in front of all the rows, I want to show it to only those rows having PDF file attached in the database.
protected void gvupdationsummary_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(st);
con.Open();
SqlCommand com = new SqlCommand("select [name],[data] from [Pragati].[dbo].[Pragati_Status_Updations] where Pragati_no=#Pragati_no", con);
com.Parameters.AddWithValue("Pragati_no", gvupdationsummary.SelectedRow.Cells[3].Text);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
Response.Clear();
Response.Buffer = true;
//Response.ContentType = dr["type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dr["name"].ToString());
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["data"]);
Response.End();
}
else
{
// ...
}
}
The code that you show seems to do the actual PDF download already. There is nothing you can do there to prevent the showing of a download button or link.
Instead you need to change the SQL query that provides data for gvupdationsummary, and add a column such as HasPDF there, like this:
SELECT /* your columns */ ,
CAST(CASE WHEN [data] IS NULL THEN 0 ELSE 1 END AS BIT) AS HasPDF
FROM ....
WHERE ....
Then in your grid rendering code you can use the boolean value of HasPDF to decide if the Download button should be shown.
Using this approach you don't needlessly transfer all PDF binary data from your database to your application, every time the grid is being rendered.
You can use SQLDataReader's IsDBNull method to see whether the column contains non-existent or missing values.
ind idx = dr.GetOrdinal("data");
if (!dr.IsDBNull(idx))
{
// set download link on to response.
}
else
{
}

Can I store difference file types into SQL Server database?

I have created a vb.net project and a SQL Server database, I want to store my other created projects to the database with some of there description. I don't know can I do that or I can store my projects files into the database in the first place. I wanted to compress my projects files to a zip file and then store the zip file to the database but I don't know if I can store these files to the database which includes a lot of file types like (jar, java, sln, vb, c#, txt ...etc)?
Thanks for your help.
Yes, you can store files in a SQL Server database table. I highly recommend you to compress them into a zip file.
First step is to create a table:
CREATE TABLE Files
(
Id INT IDENTITY PRIMARY KEY,
FileData VARBINARY(MAX) FILESTREAM NULL,
Name NVARCHAR(300)
)
and then open your zip file as stream and Insert it into your table.
OpenFileDialog openFileDlg = new OpenFileDialog();
openFileDlg.InitialDirectory = Directory.GetCurrentDirectory();
if (openFileDlg.ShowDialog() == DialogResult.OK)
{
FileInfo fi = new FileInfo(openFileDlg.FileName);
FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
BinaryReader rdr = new BinaryReader(fs);
byte[] fileData = rdr.ReadBytes((int)fs.Length);
rdr.Close();
fs.Close();
string cs = #"Data Source=<your server>;Initial Catalog=MyFsDb;Integrated Security=TRUE";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
string sql = "INSERT INTO Files VALUES (#Data, #Name)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#Data", SqlDbType.Image, fileData.Length).Value = fileData;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = fi.Name;
cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show(fi.FullName, "File Inserted!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Source : MSDN

Longer search time for shorter index in lucene

I was experimenting with Lucene on the Cystic Fybrosis collection. I made 4 indexes (seperate indexes),where one index had only title, while other had abstract and another subject. the last one had all fields.
Now I find that the search time for index which uses only title is significantly larger than for other 3 indexes. This seems counter-intuitive as the index size is small, when compared to other indices. What can be the probable reason for this?
Here is the code I have used for the benchmark
public class PrecisionRecall {
public static void main(String[] args) throws Throwable {
File topicsFile = new File("C:/Users/Raden/Documents/lucene/LuceneHibernate/LIA/lia2e/src/lia/benchmark/topics.txt");
File qrelsFile = new File("C:/Users/Raden/Documents/lucene/LuceneHibernate/LIA/lia2e/src/lia/benchmark/qrels.txt");
Directory dir = FSDirectory.open(new File("C:/Users/Raden/Documents/myindex"));
Searcher searcher = new IndexSearcher(dir, true);
String docNameField = "filename";
PrintWriter logger = new PrintWriter(System.out, true);
TrecTopicsReader qReader = new TrecTopicsReader(); //#1
QualityQuery qqs[] = qReader.readQueries( //#1
new BufferedReader(new FileReader(topicsFile))); //#1
Judge judge = new TrecJudge(new BufferedReader( //#2
new FileReader(qrelsFile))); //#2
judge.validateData(qqs, logger); //#3
QualityQueryParser qqParser = new SimpleQQParser("title", "contents"); //#4
QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, docNameField);
SubmissionReport submitLog = null;
QualityStats stats[] = qrun.execute(judge, //#5
submitLog, logger);
QualityStats avg = QualityStats.average(stats); //#6
avg.log("SUMMARY",2,logger, " ");
dir.close();
}
}
The response time of a query does not depend on index size. It depends on the number of hits and the number of terms in the query.
This is because you don't have to read all the index data. You only need to read the document list for the query terms.

How to use Lucene IndexReader to read index in version 4.4?

For the just the sake of learning I've created an index from 1 file and wanted to search it. I am using Lucene Version 4.4. I know that indexing part is true.
tempFileName is the name of file which contains tokens and this file has the following words :
"odd plus odd is even ## even plus even is even ## odd plus even is odd ##"
However when I provide a query it returns nothing. I can't see what would be the problem. Any help is greatly appreciated.
Indexing part :
public void startIndexingDocument(String indexPath) throws IOException {
Analyzer analyzer = new WhitespaceAnalyzer(Version.LUCENE_44);
SimpleFSDirectory directory = new SimpleFSDirectory(new File(indexPath));
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44,
analyzer);
IndexWriter writer = new IndexWriter(directory, config);
indexDocs(writer);
writer.close();
}
private void indexDocs(IndexWriter w) throws IOException {
Document doc = new Document();
File file = new File(tempFileName);
BufferedReader br = new BufferedReader(new FileReader(tempFileName));
Field field = new StringField(fieldName, br.readLine().toString(),
Field.Store.YES);
doc.add(field);
w.addDocument(doc);
}
Searching part :
public void readFromIndex(String indexPath) throws IOException,
ParseException {
Analyzer anal = new WhitespaceAnalyzer(Version.LUCENE_44);
QueryParser parser = new QueryParser(Version.LUCENE_44, fieldName, anal);
Query query = parser.parse("odd");
IndexReader reader = IndexReader.open(NIOFSDirectory.open(new File(
indexPath)));
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
searcher.search(query, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// display
System.out.println("fieldName =" + fieldName);
System.out.println("Found : " + hits.length + " hits.");
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i + 1) + ". " + d.get(fieldName));
}
reader.close();
}
The problem is that you are using a StringField. StringField indexes the entire input as a single token. Good for atomic strings, like keywords, identifiers, stuff like that. Not good for full text searching.
Use a TextField.
StringField have a single token. So, I try to test with simple code.
for example #yns~ If you have a file that this is cralwer file and this contents hava a single String.
ex) file name : data03.scd , contents : parktaeha
You try to search with "parktaeha" queryString.
You get the search result!
field name : acet, queryString parktaeha
======== start search!! ========== q=acet:parktaeha Found 1 hits. result array length :1 search result=> parktaeha
======== end search!! ==========
Look under the code. This code is test code.
while((target = in.readLine()) != null){
System.out.println("target:"+target);
doc.add(new TextField("acet",target ,Field.Store.YES)); // use TextField
// TEST : doc.add(new StringField("acet", target.toString(),Field.Store.YES));
}
ref url

Different analyzers for each field

How can I enable different analyzers for each field in a document I'm indexing with Lucene? Example:
RAMDirectory dir = new RAMDirectory();
IndexWriter iw = new IndexWriter(dir, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_CURRENT), true, IndexWriter.MaxFieldLength.UNLIMITED);
Document doc = new Document();
Field field1 = new Field("field1", someText1, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
Field field2 = new Field("field2", someText2, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
doc.Add(field1);
doc.Add(field2);
iw.AddDocument(doc);
iw.Commit();
The analyzer is an argument to the IndexWriter, but I want to use StandardAnalyzer for field1 and SimpleAnalyzer for field2, how can I do that? The same applies when searching, of course. The correct analyzer must be applied for each field.
PerFieldAnalyzerWrapper is what you are looking for. The equivalent of this in Lucene.net is here.
Map<String, Analyzer> analyzerMap = new HashMap<String, Analyzer>();
analyzerMap.put(fieldone, new IKAnalyzer4PinYin(false, IKAnalyzer4PinYin.PINYIN));
analyzerMap.put(fieldtwo, new IKAnalyzer4PinYin(false, KAnalyzer4PinYin.PINYIN_SHOUZIMU));
PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new IKAnalyzer4PinYin(false), analyzerMap);
IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_40 , wrapper);
Necromancing.
For C#:
Lucene.Net.Util.LuceneVersion version = Lucene.Net.Util.LuceneVersion.LUCENE_48;
Dictionary<string, Lucene.Net.Analysis.Analyzer> fieldAnalyzers =
new Dictionary<string, Lucene.Net.Analysis.Analyzer>(System.StringComparer.OrdinalIgnoreCase);
fieldAnalyzers["YourFieldName"] = new Lucene.Net.Analysis.Core.KeywordAnalyzer();
Lucene.Net.Analysis.Miscellaneous.PerFieldAnalyzerWrapper wrapper =
new Lucene.Net.Analysis.Miscellaneous.PerFieldAnalyzerWrapper(
new Lucene.Net.Analysis.Core.KeywordAnalyzer(), fieldAnalyzers);
Lucene.Net.Index.IndexWriterConfig writerConfig = new Lucene.Net.Index.IndexWriterConfig(version, wrapper);