【问题标题】:vb.net code that will export / convert multiple selected files in to one pdf file将多个选定文件导出/转换为一个pdf文件的vb.net代码
【发布时间】:2014-11-01 22:44:19
【问题描述】:

我正在尝试创建一个将多个选定文件转换为一个 pdf 文件的代码。目前,代码将选定的文件导出为 zip 文件。但我想在一个 pdf 文件中打开所有选定的文件。

为了您的帮助,我提供了将所有文件导出到一个 zip 文件中的代码。

在下面的代码中提到了两个表。一个是文件,另一个是空缺申请。在文档表中所有的文件都存储了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 的新手。感谢您的友好帮助。

【问题讨论】:

  • 您在合并 PDF 方面有什么尝试?您是否查看过 iTextSharp 库? link 可以用来将多个PDF文件合二为一。
  • 我在上面编辑了我的问题。我提供了将单个文件转换为 pdf 的代码。但我需要将多个(选定的)文件转换为一个 pdf。感谢您的帮助

标签: asp.net vb.net pdf merge itextsharp


【解决方案1】:

这是将任何文档转换为 pdf 文件并将它们合并为一个 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

要转换文档,请使用第三方库,例如 Apose Words for .net。创建一个单独的类作为转换器和一个函数 ConvertDocument(ByRef docPath As String, ByRef expPath As String) 。如果您已经拥有 pdf 格式的所有文件,则无需转换它们...

你只需要合并它们

我希望这些代码可以帮助很多人

【讨论】:

    【解决方案2】:

    这是一个将 PDF 数组合并为 1 个合并 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()
    

    【讨论】:

    • 我无法实现使用 pdf_reader 作为新的 iTextSharp.text.pdf.PdfReader(pdfs(i)) 语句。它显示实现 system.idisposable 的错误我如何在当前的 download_bulk_cv 类中实现 idisposable。我需要使用 IHttpHandler 。
    • 您可以编辑代码以显示您尝试使用 PdfReader 的位置吗?你有对 DLL 的引用吗?
    • 我已经编辑了问题并提供了代码...请查看并帮助我
    • 取出“Dim reader As New PdfReader(all_source_files(i))”这一行 - using 块负责创建/处理 PdfReader。
    • Using reader As New iTextSharp.text.pdf.PdfReader(all_source_files(i)) thisline 显示错误“iTextSharp.text.pdf.PdfReader 必须实现 system.idisposable” .. 也没有 pdf创建。我在问题中提供的更新代码创建了文档......但它只是花费第一个文件 x 时间(其中 x 是我选择的文件数)并合并同一个文件......
    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2015-02-14
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多