2014-09-08 4 views
0

여러 개의 선택된 파일을 하나의 pdf 파일로 변환하는 코드를 만들려고합니다. 현재이 코드는 선택한 파일을 zip 파일로 내 보냅니다. 그러나 선택한 모든 파일을 하나의 pdf 파일로 열려고합니다.선택한 여러 파일을 하나의 pdf 파일로 내보내거나 변환하는 vb.net 코드

귀하의 도움을 위해 모든 파일을 하나의 zip 파일로 내보내는 코드를 제공하고 있습니다.

아래 코드에는 두 개의 테이블이 나와 있습니다. 하나는 문서이고 다른 하나는 vacancyapplication입니다. 문서 테이블에서 모든 파일은 GUID가 문서 테이블의 고유 ID로 저장됩니다.

Imports System 
Imports System.Web 
Imports System.IO 
Imports System.Collections.Generic 
Imports Ionic.Zip 
Imports System.Linq 
Imports NLog 

Public Class download_bulk_cv : Implements IHttpHandler 

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest 
    Dim _logger As Logger = LogManager.GetCurrentClassLogger() 
    Dim vacancy = New Vacancy(context.Request("v")) 
    context.Response.Clear() 
    context.Response.ContentType ="application/zip" 
    context.Response.AddHeader("content-disposition", "attachment; filename=" & vacancy.Title.Replace(" ", "_") & "_" & Now.ToString("yyyy-MMM-dd-HHmmss") & ".zip") 

    Dim files = New List(Of String)() 
    For Each docPath As String In From row As DataRow In DB.GetData("select guid, originalfilename from document where id in (select candidatecvid from vacancyapplication where id in (" & context.Request("a").ToString() & "))").Rows Let guid = row.Item("guid").ToString() Select HttpContext.Current.Server.MapPath("~/documents") & "\" & Left(guid, 1) & "\" & Right(guid, 1) & "\" & guid & "." & System.IO.Path.GetExtension(row.Item("originalfilename")).ToLower().Substring(1) 
     If File.Exists(docPath) Then 
      files.Add(docPath) 
      '_logger.Info(docPath) 
     End If 
    Next 
    Using zip As New ZipFile() 
     zip.AddFiles(files.ToArray(), "CVs") '.AddFile(docPath, "CVs") 
     zip.AddEntry("info.txt", files.Count.ToString.ToString() & "CVs archived", Encoding.Default) 
     zip.Save(context.Response.OutputStream) 

    End Using 

    context.Response.End() 

End Sub 
End Class 

나는 PDF 문서를 병합하려면 다음 코드를 작성하지만


편집 코드를 작동하지 않은


Public Class preview_bulk_cv : Implements IHttpHandler 
''Implements IDisposable 


Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest 
    Dim _logger As Logger = LogManager.GetCurrentClassLogger() 
    Dim vacancy = New Vacancy(context.Request("v")) 

    Dim files = New List(Of String)() 
    Dim sourceFiles = New List(Of String)() 
    Dim directorypath As String = HttpContext.Current.Server.MapPath("~/documents") & "\download\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\" 

    Dim pdf_document As iTextSharp.text.Document = Nothing 
    Dim pdf_copier As iTextSharp.text.pdf.PdfCopy = Nothing 

    context.Response.Clear() 
    context.Response.ContentType = "application/pdf" 
    context.Response.AddHeader("content-disposition", "attachment; filename=" & vacancy.Title.Replace(" ", "_") & "_" & Now.ToString("yyyy-MMM-dd-HHmmss") & ".pdf") 

    For Each docPath As String In From row As DataRow In DB.GetData("select guid, originalfilename from document where id in (select candidatecvid from vacancyapplication where id in (" & context.Request("a").ToString() & "))").Rows Let guid = row.Item("guid").ToString() Select HttpContext.Current.Server.MapPath("~/documents") & "\" & Left(guid, 1) & "\" & Right(guid, 1) & "\" & guid & "." & System.IO.Path.GetExtension(row.Item("originalfilename")).ToLower().Substring(1) 

     Dim epath As String = HttpContext.Current.Server.MapPath("~/documents") & "\download\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\" & Now.ToString("yyyy-MMM-dd-HHmmss") & ".pdf" 
     Converter.ConvertDocument(docPath, epath) 

     If File.Exists(epath) Then 
      sourceFiles.Add(epath) 
     End If 

     If File.Exists(docPath) Then 
      files.Add(docPath) 
      '_logger.Info(docPath) 
     End If 
    Next 

    Dim all_source_files As String() = sourceFiles.ToArray() 


    Dim docs As PdfDocument() = New PdfDocument(all_source_files.Length - 1) {} 

    For i As Integer = 0 To all_source_files.Length - 1 

     Dim reader As New PdfReader(all_source_files(i)) 

    ' Using reader As New iTextSharp.text.pdf.PdfReader(all_source_files(i)) 

     Dim finalpdf As String = HttpContext.Current.Server.MapPath("~/documents") & "\download\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\finalcv.pdf" 

     If i = 0 Then 
      pdf_document = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)) 
      pdf_copier = New iTextSharp.text.pdf.PdfCopy(pdf_document, New IO.FileStream(finalpdf, IO.FileMode.Create)) 
      pdf_document.Open() 
     End If 

     For page_num As Integer = 1 To reader.NumberOfPages 
      pdf_copier.AddPage(pdf_copier.GetImportedPage(reader, page_num)) 
     Next 

     ' End Using 

    Next 

    pdf_copier.Close() 


End Sub 

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable 
    Get 
     Return False 
    End Get 
End Property 

End Class  

vb.net에서 새로 생겼습니다. 당신의 친절한 도움에 감사드립니다.

+0

도움이 될 것입니다 희망을 그들에게

을 병합해야

... 변환 할 필요가없는 PDF를 결합 하시겠습니까? iTextSharp 라이브러리를 살펴 보셨습니까? [link] (http://sourceforge.net/projects/itextsharp/) 여러 개의 PDF 파일을 하나로 결합하는 데 사용할 수 있습니다. –

+0

위의 질문을 편집했습니다. 단일 파일을 pdf로 변환하는 코드를 제공했습니다. 하지만 하나의 pdf로 여러 파일을 변환해야합니다. 귀하의 친절한 도움을 주셔서 감사합니다 – Bashabi

답변

2

이것은 PDF 배열을 하나의 병합 된 PDF로 결합하는 코드의 예입니다. 주석에 언급 된 iTextSharp dll에 대한 참조가 필요합니다. 각 파일을 개별적으로 PDF에 저장할 수 있다면 System.IO.Directory.GetFiles (your_directory)와 같은 것을 사용하여 파일 이름의 배열을 가져온 다음 여기에 코드와 같은 내용을 결합 할 수 있습니다.

' This requires a reference to the iTextSharp library (http://sourceforge.net/projects/itextsharp/) 
    Dim pdfs() As String ' all of your PDF files you'd like to merge 
    Dim output_pdf As String ' the output file 

    Dim pdf_document As iTextSharp.text.Document = Nothing 
    Dim pdf_copier As iTextSharp.text.pdf.PdfCopy = Nothing 

    For i As Integer = 0 To pdfs.Length - 1 
     Using pdf_reader As New iTextSharp.text.pdf.PdfReader(pdfs(i)) 
      If i = 0 Then 
       pdf_document = New iTextSharp.text.Document(pdf_reader.GetPageSizeWithRotation(1)) 
       pdf_copier = New iTextSharp.text.pdf.PdfCopy(pdf_document, New IO.FileStream(output_pdf, IO.FileMode.Create)) 
       pdf_document.Open() 
      End If 

      For page_num As Integer = 1 To pdf_reader.NumberOfPages 
       pdf_copier.AddPage(pdf_copier.GetImportedPage(pdf_reader, page_num)) 
      Next 
     End Using 
    Next 

    pdf_copier.Close() 
+0

새로운 iTextSharp.text.pdf.PdfReader (pdfs (i)) 문으로 pdf_reader 사용을 구현할 수 없습니다. system.idisposable을 구현하는 데 오류가 있음 현재 download_bulk_cv 클래스에 idisposable을 구현하려면 어떻게해야합니까? IHttpHandler를 사용해야합니다. – Bashabi

+0

PdfReader를 사용하려는 위치를 나타내는 코드를 편집 할 수 있습니까? DLL에 대한 참조가 있습니까? –

+0

나는 질문을 편집하고 코드를 제공했습니다 ... 제발 좀 보살펴주세요. – Bashabi

1

여기에 PDF 파일로 문서를 변환하고 문서가 .NET 용 Apose 단어와 같은 타사 라이브러리를 사용하여 변환하려면 하나 개의 PDF 파일

<%@ WebHandler Language="VB" Class="PDFMerge" %> 

Imports System 
Imports System.Web 
Imports System.IO 
Imports System.Collections.Generic 
Imports Ionic.Zip 
Imports System.Linq 
Imports NLog 
Imports iTextSharp.text 
Imports iTextSharp.text.pdf 
Imports System.Text.RegularExpressions 


Public Class PDFMerge : Implements IHttpHandler 




Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest 
    Dim _logger As Logger = LogManager.GetCurrentClassLogger() 
    Dim vacancy = New Vacancy(context.Request("v")) 

    Dim sourceFiles = New List(Of String)() 


    For Each docPath As String In From row As DataRow In DB.GetData("database query").Rows Select HttpContext.Current.Server.MapPath("~/Downloads") & "\" System.IO.Path.GetExtension(row.Item("originalfilename")).ToLower().Substring(1) 


     Dim epath As String = HttpContext.Current.Server.MapPath("~/Downloads") & "\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\" & Now.ToString("yyyy-MMM-dd-HHmmss") & ".pdf" 

     Converter.ConvertDocument(docPath, epath) 

     If File.Exists(epath) Then 
      sourceFiles.Add(epath) 
     End If 


    Next 

    Dim OutputFileName As String = HttpContext.Current.Server.MapPath("~/Downloads") & "\" & Now.ToString("yyyy-MMM-dd") & "\" & vacancy.Title.Replace(" ", "_") & "\" & vacancy.Title.Replace(" ", "_") & ".pdf" 

    PDFMerge.MergeFiles(OutputFileName, sourceFiles.ToArray) 
    Dim mPDFFile As FileStream = File.OpenRead(OutputFileName) 
    Dim mPDFFileBuffer(mPDFFile.Length - 1) As Byte 
    mPDFFile.Read(mPDFFileBuffer, 0, mPDFFileBuffer.Length) 
    mPDFFile.Close() 

    System.Diagnostics.Process.Start(OutputFileName) 



    context.Response.Clear() 
    context.Response.ContentType = "application/pdf" 
    context.Response.AddHeader("Content-Disposition", "attachment;filename=" & OutputFileName) 

    context.Response.AddHeader("Content-Length", mPDFFileBuffer.Length) 
    context.Response.OutputStream.Write(mPDFFileBuffer, 0, mPDFFileBuffer.Length) 
    mPDFFileBuffer = Nothing 
    context.Response.Flush() 
    context.Response.End() 



End Sub 



Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable 
    Get 
     Return False 
    End Get 
End Property 

Public Shared Sub MergeFiles(destinationFile As String, sourceFiles As String()) 


    Try 
     Dim f As Integer = 0 
     Dim reader As New PdfReader(sourceFiles(f))  ' we create a reader for a certain document 
     Dim n As Integer = reader.NumberOfPages   ' we retrieve the total number of pages 

     'Console.WriteLine("There are " + n + " pages in the original file."); 

     Dim document As New Document(reader.GetPageSizeWithRotation(1))    ' step 1: creation of a document-object 
     Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream(destinationFile, FileMode.Create))    ' step 2: we create a writer that listens to the document 
     document.Open()    ' step 3: we open the document 

     Dim cb As PdfContentByte = writer.DirectContent 
     Dim page As PdfImportedPage 
     Dim rotation As Integer 

     ' step 4: we add content 
     While f < sourceFiles.Length 
      Dim i As Integer = 0 
      While i < n 
       i += 1 
       document.SetPageSize(reader.GetPageSizeWithRotation(i)) 
       document.NewPage() 
       page = writer.GetImportedPage(reader, i) 
       rotation = reader.GetPageRotation(i) 
       If rotation = 90 OrElse rotation = 270 Then 
        cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, _ 
        reader.GetPageSizeWithRotation(i).Height) 
       Else 
        cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, _ 
        0) 
        'Console.WriteLine("Processed page " + i); 
       End If 
      End While 
      f += 1 
      If f < sourceFiles.Length Then 
       reader = New PdfReader(sourceFiles(f)) 
       ' we retrieve the total number of pages 
       'Console.WriteLine("There are " + n + " pages in the original file."); 
       n = reader.NumberOfPages 
      End If 
     End While 
     ' step 5: we close the document 
     document.Close() 
    Catch e As Exception 
     Dim strOb As String = e.Message 
    End Try 
End Sub 

Public Function CountPageNo(strFileName As String) As Integer 
    ' we create a reader for a certain document 
    Dim reader As New PdfReader(strFileName) 
    ' we retrieve the total number of pages 
    Return reader.NumberOfPages 
End Function 


End Class 

로 병합 코드입니다. 변환기 및 함수로 별도의 클래스를 만듭니다. ConvertDocument (ByRef docPath As String, ByRef expPath As String). 이미 PDF에있는 모든 파일이 있다면 당신은 내가이 코드는 당신이 지금까지와 같은 시도 무엇 많은 사람들