현재 저는 다양한 PDF를 생성 할 수있는 PDF 웹앱 개발을 마쳤습니다. 그러나 사용자가 액세스 할 때 휴대폰과 컴퓨터 모두에 대한 공통 다운로드 PDF 디렉토리가 있어야합니다.
지금은 localhost에서 웹 응용 프로그램을 실행하려고 할 때 이것이 PDF 파일을 저장하는 방법입니다. 그러나 내 webapp을 온라인에 게시했을 때 모든 컴퓨터에 비슷한 파일 디렉토리가있는 것은 아닙니다.
var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
따라서 휴대 전화와 컴퓨터의 공통 파일 디렉토리에 대한 아이디어가 있는지 물어보고 싶습니다.
PDF 버튼
protected void btnPDF_Click(object sender, EventArgs e)
{
var doc1 = new Document();
var filename = "MyTestPDF" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
doc1.Open();
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 585f;
table.LockedWidth = true;
var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/image/logo.jpg"));
doc1.Add(logo);
var titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD);
doc1.Add(new Paragraph("Officer's Profile. Officer's Police ID: " + DDLCase.SelectedValue, titleFont));
var normalFont = FontFactory.GetFont(FontFactory.HELVETICA, 14, Font.BOLD);
var phrase = new Phrase();
SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security = SSPI");
SqlCommand cm = new SqlCommand("Select lrp.fullname, pp.profilepic, pp.rank, lrp.policeid, lrp.nric, lrp.email, lrp.contact, lrp.address,lrp.location, pp.achievement, pp.medal1, pp.medal2, pp.medal3, pp.medal4, pp.medal5 from LoginRegisterPolice lrp, PoliceProfile pp where lrp.policeid = '" + DDLCase.SelectedValue + "' and pp.policeid = lrp.policeid", con);
con.Open();
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
phrase.Add(new Chunk("Full Name :", normalFont));
phrase.Add(dr[0].ToString());
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Profile Picture :\u00a0", normalFont));
Byte[] bytes1 = (Byte[])dr[1];
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(bytes1);
image1.ScaleToFit(100f, 250f);
Chunk imageChunk1 = new Chunk(image1, 0, 0);
phrase.Add(imageChunk1);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Rank : ", normalFont));
Byte[] bytes2 = (Byte[])dr[2];
iTextSharp.text.Image image2 = iTextSharp.text.Image.GetInstance(bytes2);
image2.ScaleToFit(40f, 300f);
Chunk imageChunk2 = new Chunk(image2, 0, 0);
phrase.Add(imageChunk2);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Police ID :", normalFont));
phrase.Add(dr[3].ToString());
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("NRIC :", normalFont));
phrase.Add(dr[4].ToString());
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Email :", normalFont));
phrase.Add(dr[5].ToString());
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Contact :", normalFont));
phrase.Add(dr[6].ToString());
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Address :", normalFont));
phrase.Add(dr[7].ToString());
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Location :", normalFont));
phrase.Add(dr[8].ToString());
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Achievement :", normalFont));
phrase.Add(dr[9].ToString());
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(Chunk.NEWLINE);
phrase.Add(new Chunk("Medal1", normalFont));
Byte[] bytes3 = (Byte[])dr[10];
iTextSharp.text.Image image3 = iTextSharp.text.Image.GetInstance(bytes3);
image3.ScaleToFit(800f, 800f);
Chunk imageChunk3 = new Chunk(image3, 0, 0);
phrase.Add(imageChunk3);
phrase.Add(new Chunk("Medal2", normalFont));
Byte[] bytes5 = (Byte[])dr[11];
iTextSharp.text.Image image5 = iTextSharp.text.Image.GetInstance(bytes5);
image5.ScaleToFit(800f, 800f);
Chunk imageChunk5 = new Chunk(image5, 0, 0);
phrase.Add(imageChunk5);
phrase.Add(new Chunk("Medal3", normalFont));
Byte[] bytes6 = (Byte[])dr[12];
iTextSharp.text.Image image6 = iTextSharp.text.Image.GetInstance(bytes6);
image6.ScaleToFit(800f, 800f);
Chunk imageChunk6 = new Chunk(image6, 0, 0);
phrase.Add(imageChunk6);
phrase.Add(new Chunk("Medal4", normalFont));
Byte[] bytes7 = (Byte[])dr[13];
iTextSharp.text.Image image7 = iTextSharp.text.Image.GetInstance(bytes7);
image7.ScaleToFit(800f, 800f);
Chunk imageChunk7 = new Chunk(image7, 0, 0);
phrase.Add(imageChunk7);
phrase.Add(new Chunk("Medal5", normalFont));
Byte[] bytes8 = (Byte[])dr[14];
iTextSharp.text.Image image8 = iTextSharp.text.Image.GetInstance(bytes8);
image8.ScaleToFit(800f, 800f);
Chunk imageChunk8 = new Chunk(image8, 0, 0);
phrase.Add(imageChunk8);
table.AddCell(phrase);
}
dr.Close();
doc1.Add(table);
doc1.Close();
btnPDF.Enabled = false;
}
}
좋아요, 귀하의 의견을 바탕으로 도움이 되었기를 바랍니다.
의 두 번째 매개 변수 iTextSharp.text.pdf.PdfWriter.GetInstance()
는 실제로 일반 System.IO.Stream
객체입니다. 즉, 해당 개체에서 상속 된 모든 개체를 전달할 수 있습니다. 몇 가지 유형이 있지만이 경우 가장 도움이되는 두 가지 유형은 System.IO.FileStream
일반적으로 및 System.IO.MemoryStream
. 이 MemoryStream
클래스는 기본적으로 "인 메모리 파일"과 같지만 다행히도 그것에 대해 생각할 필요가 없습니다. a를 사용할 때의 관점과 다른 MemoryStream
점은 닫았을 때 Document
바이트를 추출해야하며 한 줄로 수행 할 수 있다는 것입니다.
다음은이를 보여주는 샘플 코드입니다. 먼저 우리가 나중에 우리의 PDF를 저장하는거야 바이트의 빈 배열을 만듭니다. 그런 다음에 생성 MemoryStream
대신의 FileStream
. 그런 다음 매우 간단한 PDF를 생성합니다. 완료되면 MemoryStream
위에서 만든 바이트 배열로 바이트를 덤프합니다 . 그 후 iTextSharp는 더 이상 관여하지 않으며 ASP.Net 만 다루고 있습니다.
(참고 :에 쓰는 대신 MemoryStream
, 바이트를 추출하여 브라우저로 펌핑하는 대신에 사람들 Response.OutputStream
이에 직접 쓰는 것을 종종 볼 수 있습니다. 이것은 100 % 유효하지만 디버깅하기가 더 어려울 수 있으므로 사용하지 않는 것이 좋습니다. 내 iTextSharp가 먼저 작동하고 오류를 디버그 한 다음 ASP.Net 및 브라우저 문제를 처리하십시오.)
protected void btnPDF_Click(object sender, EventArgs e) {
//Byte array that will eventually hold our PDF, currently empty
Byte[] bytes;
//Instead of a FileStream we'll use a MemoryStream
using (var MS = new System.IO.MemoryStream()) {
//Standard PDF setup, iText doesn't care what type of stream we're using
var doc = new iTextSharp.text.Document();
var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, MS);
doc.Open();
doc.Add(new iTextSharp.text.Paragraph("Hello world"));
doc.Close();
//Grab the raw bytes from the MemoryStream
bytes = MS.ToArray();
}
//At this point all iText work is done and we're only dealing with raw ASP.Net parts
//Clear the current response buffer
Response.Clear();
//Instead of a normal text/html header tell the browser that we've got a PDF
Response.ContentType = "application/pdf";
//Tell the browser that you want the file downloaded (ideally) and give it a pretty filename
Response.AddHeader("content-disposition", "attachment;filename=MySampleFile.pdf");
//Write our bytes to the stream
Response.BinaryWrite(bytes);
//Close the stream (otherwise ASP.Net might continue to write stuff on our behalf)
Response.End();
}
또한 이것은 사용자의 브라우저 가 다운로드 해야하는 파일을 생성합니다 . 그러나 브라우저 및 사용자가 브라우저를 구성한 방법에 따라 다른 결과를 얻을 수 있습니다. 예를 들어, 내 컴퓨터의 Google 크롬은 이전에 설정 한 현재 다운로드 폴더로 파일을 즉시 다운로드합니다. 반면에 Mozilla Firefox는 파일을 저장할 위치를 선택하라는 메시지를 표시합니다. (어떤 이유로 내 Internet Explorer가 오늘 localhost와 대화하고 싶지 않아서 무엇을할지 모르겠습니다.)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다