pdf merge for code one

本文将介绍使用Java和iText库合并两个PDF文件的方法,并提供代码示例。

Merging Two PDF documents to One

http://www.java2s.com/Code/Java/PDF-RTF/MergingTwoPDFdocumentstoOne.htm

import java.io.FileOutputStream;

import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class MergingTwoPDFToOne {
  public static void main(String[] args) {
    try {
      PdfReader reader = new PdfReader("YourOwnPDF.pdf");

      PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("TwoPDF.pdf"));

      PdfContentByte under;

      PdfReader reader2 = new PdfReader("AnotherPDF.pdf");
      under = stamp.getUnderContent(1);
      under.addTemplate(stamp.getImportedPage(reader2, 1), 1, 0, 0, 1, 0, 0);

      stamp.close();
    } catch (Exception de) {
      de.printStackTrace();
    }
  }
}
           

//以上代码测试不成功  


How to Merge PDF Files in iText

http://www.ehow.co.uk/how_7427980_merge-pdf-files-itext.html

Instructions

    • 1

      Use the code to create a list of InputStream from the all the input PDFs. This should be done in main() method. Call MergePDF.concatPDFs() static method for a list of input PDFs and OutputStream object for the merged output PDF. A boolean flag represents the inclusion of page numbers as page line arguments.

    • 2

      Convert the list of InputStream objects to a list of PDFReader objects using the concatPDFs() method, for each input PDF, while also creating a list of InputStream. Then, create a document object for the merged PDF.

    • 3

      Create a PDFWriter for the desired OutputStream. Additionally, you can add page numbers to your document, and the font these numbers will be written in, using BaseFont.createFont() method. Write the merged PDF file using the Document class object and PdfWriter.getInstance() method.

    • 4

      Write the individual pages to the merged PDF output, then add text at the bottom of the page. Finally, close all streams and clear the buffers.



Read more: How to Merge PDF Files in iText | eHow.co.uk http://www.ehow.co.uk/how_7427980_merge-pdf-files-itext.html#ixzz1dklXZFEO


http://viralpatel.net/blogs/2009/06/itext-tutorial-merge-split-pdf-files-using-itext-jar.html

package net.viralpatel.itext.pdf;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
import com.lowagie.text.Document;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
 
public class MergePDF {
 
    public static void main(String[] args) {
        try {
            List<InputStream> pdfs = new ArrayList<InputStream>();
            pdfs.add(new FileInputStream("c:\\1.pdf"));
            pdfs.add(new FileInputStream("c:\\2.pdf"));
            OutputStream output = new FileOutputStream("c:\\merge.pdf");
            MergePDF.concatPDFs(pdfs, output, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void concatPDFs(List<InputStream> streamOfPDFFiles,
            OutputStream outputStream, boolean paginate) {
 
        Document document = new Document();
        try {
            List<InputStream> pdfs = streamOfPDFFiles;
            List<PdfReader> readers = new ArrayList<PdfReader>();
            int totalPages = 0;
            Iterator<InputStream> iteratorPDFs = pdfs.iterator();
 
            // Create Readers for the pdfs.
            while (iteratorPDFs.hasNext()) {
                InputStream pdf = iteratorPDFs.next();
                PdfReader pdfReader = new PdfReader(pdf);
                readers.add(pdfReader);
                totalPages += pdfReader.getNumberOfPages();
            }
            // Create a writer for the outputstream
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
 
            document.open();
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
            // data
 
            PdfImportedPage page;
            int currentPageNumber = 0;
            int pageOfCurrentReaderPDF = 0;
            Iterator<PdfReader> iteratorPDFReader = readers.iterator();
 
            // Loop through the PDF files and add to the output.
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = iteratorPDFReader.next();
 
                // Create a new page in the target for each source page.
                while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                    document.newPage();
                    pageOfCurrentReaderPDF++;
                    currentPageNumber++;
                    page = writer.getImportedPage(pdfReader,
                            pageOfCurrentReaderPDF);
                    cb.addTemplate(page, 0, 0);
 
                    // Code for pagination.
                    if (paginate) {
                        cb.beginText();
                        cb.setFontAndSize(bf, 9);
                        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                                + currentPageNumber + " of " + totalPages, 520,
                                5, 0);
                        cb.endText();
                    }
                }
                pageOfCurrentReaderPDF = 0;
            }
            outputStream.flush();
            document.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen())
                document.close();
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}


merge pdf into one source code java


import java.io.File;
import java.net.ConnectException;
import java.util.Date;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class Test {
	
	public void docToPdf(File inputFile, File outputFile){
		OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
	    try{
	    	connection.connect();
	    	
	    	 // convert
		    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
		    converter.convert(inputFile, outputFile);
	    }catch(ConnectException cex){
	    	cex.printStackTrace();
	    }finally{
		    // close the connection
	    	if(connection!=null){
	    		connection.disconnect();
	    		connection = null;
	    	}
	    }
	    long l = (start.getTime()- new Date().getTime());
	    long day=l/(24*60*60*1000);
	       long hour=(l/(60*60*1000)-day*24);
	       long min=((l/(60*1000))-day*24*60-hour*60);
	       long s=(l/1000-day*24*60*60-hour*60*60-min*60);
	       System.out.println("生成"+outputFile.getName()+"耗费:"+min+"分"+s+"秒");
	}
}




### 使用 Stirling PDF API 进行调用 Stirling-PDF 是一个功能丰富的本地托管Web应用程序,允许用户对PDF文件执行多种操作。为了更好地理解如何使用其API进行调用,下面提供了详细的说明和示例。 #### 获取API访问权限 由于Stirling-PDF旨在保护用户的隐私并确保安全,在使用API之前需确认已正确设置了`.env`文件中的必要参数[^3]。这通常涉及设置API密钥或其他认证机制来验证请求的有效性。 #### 发送HTTP请求到API端点 大多数情况下,与Stirling-PDF交互的方式是通过发送标准的HTTP POST或GET请求至特定URL路径下的API接口。这些路径对应于不同的PDF处理功能,比如合并、拆分或是转换等。 对于具体的API调用方法,假设存在如下几个常见的RESTful风格API: - **上传单个PDF文件** URL: `/api/upload` Method: `POST` Headers: - Content-Type: multipart/form-data Body (form data): - file: 文件流形式的PDF文档 - **获取所有可用的操作列表** URL: `/api/operations` Method: `GET` Response Example: ```json { "operations": [ {"name":"merge", "description":"Merge multiple PDFs into one."}, {"name":"split", "description":"Split a single PDF into separate pages."} // 更多... ] } ``` - **执行指定名称的操作** 假设要执行名为`merge`的操作,则可以通过向相应的API端点提交包含所需输入数据(如待合并的PDF ID数组)的JSON对象来进行。 URL: `/api/operation/{operationName}` Method: `POST` Headers: - Authorization: Bearer YOUR_ACCESS_TOKEN - Content-Type: application/json Body (raw JSON): ```json { "inputFilesIds":[1,2], "outputFileName":"merged_document.pdf" } ``` 以上仅为简化版的例子;实际使用的API可能有所不同,请参阅官方提供的最新文档以获得最准确的信息[^4]。 ```python import requests url = 'http://localhost:8080/api/upload' files = {'file': open('example.pdf', 'rb')} response = requests.post(url, files=files) if response.status_code == 200: print("File uploaded successfully.") else: print(f"Failed to upload file with status code {response.status_code}.") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值