Required DLL itextsharp DLL - Search and add in the right-click reference "manage NuGet package" of VS
call
private void button1_Click(object sender, EventArgs e) { //String [] filenames = new string [] {"C: \ \ users \ \ baa figure \ \ Desktop \ \ new folder \ \ K186+020 laojunlu bridge \ \ bridge type layout 1.pdf", // "C:\Users \ \ Desktop \ \ new folder \ \ K186+020 laojunlu bridge \ \ bridge type layout 2.pdf"}; //string outputFile = "C:\D disk"; //PdfDocumentBase doc = PdfDocument.MergeFiles(fileNames); //doc.Save(outputFile); //MessageBox.Show("merge succeeded"); MergePDF(textBox1.Text+","+textBox2.Text, "C:\\D disc","merge.pdf"); }
Tool function
private void MergePDF(string PdfFileNames, string outMergeFile, string FileName) { string subPath = outMergeFile + "\\temp\\"; subPath = ""; string[] fileList = PdfFileNames.Split(','); if (fileList.Length < 1) { return; } try { PdfReader reader; iTextSharp.text.Rectangle rectangle = new iTextSharp.text.Rectangle(PageSize.A3.Height, PageSize.A3.Width); iTextSharp.text.Document document = new iTextSharp.text.Document(rectangle); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile + "\\" + FileName, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage newPage; BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); int countNum = 0; for (int i = 0; i < fileList.Length; i++) { if (fileList[i].Contains(".docx")) { fileList[i] = fileList[i].Replace(".docx", ".pdf"); } else if (fileList[i].Contains(".doc")) { fileList[i] = fileList[i].Replace(".doc", ".pdf"); } if (!File.Exists(subPath + fileList[i])) { continue; } reader = new PdfReader(subPath + fileList[i]); int iPageNum = reader.NumberOfPages; for (int j = 1; j <= iPageNum; j++) { countNum += 1; document.NewPage(); newPage = writer.GetImportedPage(reader, j); String text = countNum.ToString(); float len = bf.GetWidthPoint(text, 10); cb.AddTemplate(newPage, 0, 0); cb.BeginText(); cb.SetFontAndSize(bf, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, text, 530, 20, 0); //cb.SetTextMatrix(0, 0); //cb.ShowText(text); cb.EndText(); //cb.AddTemplate(newPage, 0, 0); } } if (document != null) { document.Close(); } if (Directory.Exists(subPath)) Directory.Delete(subPath, true);//Delete temporary folder } catch (Exception) { string message = "File:" + outMergeFile + "\\" + FileName + "Merge failed."; MessageBox.Show(message); } }
Turn from https://www.cnblogs.com/matrix-zhu/p/6305944.html
IText implements the basic setting of PDF document properties
1, Introduction to Itext
iText is a project of sourceforge, a famous open source site. It is a java class library for generating PDF documents. iText can not only generate PDF or rtf documents, but also convert XML and Html files into PDF files.
IText is very easy to install in http://www.lowagie.com/iText/download.html Download itext.com from the website Jar file, you only need to add iText.jar in the CLASSPATH of the system Jar, you can use iText class library in your program.
2, To generate a PDF
1. Create a document object instance
Document document = new Document();
2. Establish the association between the Writer and the document object, and write the document to disk through the Writer
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
DEST: generate PDF file
3. Open document
document.open();
4. Add content to document
document.add(new Paragraph("PDF demo"));
5. Close document
document.close();
3, Specific analysis
1. Object instance
public document();
public document(Rectangle pageSize);
public document(Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom);
pageSize refers to the document page size, public document(); The page size is A4, and the effect is equivalent to Document(PageSize.A4);
14882 13823 15981 25113 14882 8916 18294 25113 14882 18368 30020 27983 14882 1460 25933 25662 17812 18264 15981 25113 3427 25113 11184 27983 5594 22371 31188 29618
Through the parameter pageSize, you can set properties such as page size, face back color, and page landscape / portrait. iText defines A0-A10, AL, LETTER, HALFLETTER_ 11x17,LEDGER,NOTE,B0-B5,ARCH_A-ARCH_E. For FLSA, FLSE and other paper types, you can also use Rectangle pageSize = new Rectangle(144, 720); Custom paper. You can set the page to landscape through the Rectangle method rotate().
2. Writer object
Once the document object is established, one or more writer objects need to be associated with it. Through the writer object, you can save specific documents into the required format.
PDFWriter can save documents as PDF files; HtmlWriter can save documents as html files
3. Document properties
Before opening a document, you can set the title, subject, author, keyword, binding method, creator, producer, creation date and other attributes of the document. The methods called are:
public boolean addTitle(String title)
public boolean addSubject(String subject)
public boolean addKeywords(String keywords)
public boolean addAuthor(String author)
public boolean addCreator(String creator)
public boolean addProducer()
public boolean addCreationDate()
public boolean addHeader(String name, String content)
The method addHeader is not valid for PDF documents, and addHeader is only valid for html documents. It is used to add the header information of documents.
Before a new page is generated, you can set the page size, bookmark, header footer and other information. The method you call is:
public boolean setPageSize(Rectangle pageSize)
public boolean add(Watermark watermark)
public void removeWatermark()
public void setHeader(HeaderFooter header)
public void resetHeader()
public void setFooter(HeaderFooter footer)
public void resetFooter()
public void resetPageCount()
public void setPageCount(int pageN)
If you want to set the first page properties, these methods must be called before the document is opened.
For PDF documents, iText also provides the display properties of the document. By calling the setViewerPreferences method of the writer, you can control the display properties of Acrobat Reader when the document is opened, such as single page display, full screen display, hidden status bar and so on.
In addition, iText also provides security protection for PDF files. Through the setEncryption method of the Writer, you can set the user password, read-only, printable and other attributes of the document.
4. Add document content
All content added to the document is based on objects, such as phase, Paragraph, Table, Graphic objects, etc. The more common is the Paragraph object, which is used to add a Paragraph of text to the document.
IText processes text with chunks, phrases, and paragraphs. The text block (Chunk) is the smallest unit for processing text. It is composed of a string with format (including font, color and size). For example, the following code generates an underlined string with a font of HELVETICA, a size of 10:
Chunk chunk1 = new Chunk("This text is underlined",
FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE));
A phrase consists of one or more text blocks (chunks). A phrase (Phrase) can also set a font, but it is invalid for the text block (Chunk) in which the font has been set. A chunk of text can be added to a phrase through the phrase member function add, such as phrase 6 add(Chunk);
A paragraph is composed of one or more chunks or phrases, which is equivalent to the paragraph concept in a WORD document. You can also set the font size, color and other attributes of the paragraph. In addition, you can also set the indentation and alignment of the first line of the paragraph (left alignment, right alignment, center alignment). The paragraph alignment can be set through the function setAlignment. The parameters of setAlignment are 1 for center alignment, 2 for right alignment, and 3 for left alignment. The default is left alignment.
There are PDFTable and Table in Itext. For simple Table processing, you can use Table, but if you want to process complex tables, you need PDFTable to process them.
When creating a table, you must specify columns, but rows are not required.
After creating a table, you can set the table properties, such as border width, border color, padding space (i.e. the spacing between cells) and so on.
The Image processing class in iText is Image. At present, the Image formats supported by iText include GIF, Jpeg, PNG, wmf and other formats. For different Image formats, iText automatically recognizes the Image format with the same constructor. Examples of gif, jpg and png images are obtained through the following code.
Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png");
Image location
The position of image mainly refers to the alignment of image in document and the position relationship between image and text. IText is processed through the function public void setAlignment(int alignment), and the parameter alignment is image RIGHT,Image.MIDDLE,Image.LEFT refers to right alignment, center alignment and left alignment respectively; When the parameter alignment is image TEXTWRAP,Image.UNDERLYING refers to the display of text around graphics and graphics as the background of text. These two parameters can be combined to achieve the desired effect. For example, the effect of setAlignment(Image.RIGHT|Image.TEXTWRAP) is that the image is aligned right and the text is displayed around the image.
Image size and rotation
If the image is not displayed according to the original size in the document, it can be set through the following function:
public void scaleAbsolute(int newWidth, int newHeight)
public void scalePercent(int percent)
public void scalePercent(int percentX, int percentY)
The function public void scaleAbsolute(int newWidth, int newHeight) directly sets the display size;
The function public void scalepercent (int percent) sets the display scale. For example, scalePercent(50) indicates that the display size is 50% of the original size;
The function scalePercent(int percentX, int percentY) is the display ratio of the image height and width.
If the image needs to be rotated by a certain angle and displayed in the document, it can be set through the function public void setRotation(double r). The parameter r is radian. If the rotation angle is 30 degrees, the parameter r = math PI/6.
4, Chinese processing
The default iText font setting does not support Chinese fonts. You need to download the Far East font package itextasian Jar, otherwise Chinese fonts cannot be output to PDF documents. You can use Chinese in the document through the following code:
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
perhaps
BaseFont bfChinese = BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);,
Note: case sensitive here! For example, the English name in Song typeface is simsun (note that it is not simsun!, the initials are capitalized)
Incorrect writing: font-family:Tahoma or font-family:simsun Correct writing: font-family:SimSun perhaps font-family:SimHei
Make sure that all the above fonts are added through addFont. If the font name is wrong or the font does not exist, an exception will be thrown. It is very convenient, but the font that is not imported will not be prompted.
5, Examples
1. IText adds a watermark and increases permissions
@Test public void addWaterMark() throws Exception{ String srcFile="D:\\work\\pdf\\win10.pdf";//File to add watermark String text="System integration company";//Content to add watermark int textWidth=200; int textHeight=440; PdfReader reader = new PdfReader(srcFile);// Documents to be watermarked PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File("D:\\work\\pdf\\addWaterMark.pdf")));// Watermarked file // byte[] userPassword = "123".getBytes(); byte[] ownerPassword = "12345".getBytes(); // int permissions = PdfWriter.ALLOW_COPY|PdfWriter.ALLOW_MODIFY_CONTENTS|PdfWriter.ALLOW_PRINTING; // stamper.setEncryption(null, ownerPassword, permissions,false); stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_ASSEMBLY, false); stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_COPY, false); stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_DEGRADED_PRINTING, false); stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_FILL_IN, false); stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_ANNOTATIONS, false); stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_CONTENTS, false); stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_PRINTING, false); stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_SCREENREADERS, false); stamper.setEncryption(null, ownerPassword, PdfWriter.DO_NOT_ENCRYPT_METADATA, false); stamper. setViewerPreferences(PdfWriter.HideToolbar|PdfWriter.HideMenubar); // stamper.setViewerPreferences(PdfWriter.HideWindowUI); int total = reader.getNumberOfPages() + 1; PdfContentByte content; BaseFont font = BaseFont.createFont("font/SIMKAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); for (int i = 1; i < total; i++)// Loop to insert watermark on each page { content = stamper.getUnderContent(i);// Watermark start content.beginText();// start content.setColorFill(BaseColor.GREEN);// Set the color to blue by default content.setFontAndSize(font, 38);// Set font and size content.setTextMatrix(textWidth, textHeight);// Set start position content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);// Start writing watermark content.endText(); } stamper.close(); }
2. Bookmark IText
Document document = new Document(PageSize.A4); BaseFont bfCN = BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // Font of Chapter Font chFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLUE); // Section font Font secFont = new Font(bfCN, 12, Font.NORMAL, new BaseColor(0, 204, 255)); // Font of body Font textFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLACK); PdfWriter.getInstance(document, new FileOutputStream(DEST)); document.open(); int chNum = 1; Chapter chapter = new Chapter(new Paragraph("Michael introduce", chFont), chNum++); Section section = chapter.addSection(new Paragraph("essential information", secFont)); section.setIndentation(10); section.setIndentationLeft(10); section.setBookmarkOpen(true); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); section.add(new Paragraph("A hard pressed code farmer...", textFont)); Section section2 = chapter.addSection(new Paragraph("SNS", secFont)); section2.setIndentation(10); section2.setIndentationLeft(10); section2.setBookmarkOpen(false); section2.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); section2.add(new Paragraph("SNS Address classification:", textFont)); section = section2.addSection(new Paragraph(new Chunk("My blog", secFont) .setUnderline(0.2f, -2f).setAnchor("http://www.cnblogs.com/xiaoSY-learning"))); section.setBookmarkOpen(false); section.setIndentation(10); section.setIndentationLeft(10); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); section.add(new Paragraph(new Chunk("my blog Address: http://www.cnblogs.com/xiaoSY-learning/", textFont).setUnderline(0.2f, -2f).setAnchor( "http://www.cnblogs.com/xiaoSY-learning/"))); section.add(new Paragraph("Share your technical experience.", textFont)); section = section2.addSection(new Paragraph(new Chunk("my weibo", secFont).setUnderline(0.2f, -2f).setAnchor( "http://weibo.com/u/2772113512"))); section.setIndentation(10); section.setIndentationLeft(10); section.setBookmarkOpen(false); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); section.add(new Paragraph(new Chunk("my weibo: http://weibo.com/u/2772113512", textFont).setUnderline(0.2f, -2f).setAnchor( "http://weibo.com/u/2772113512"))); section.add(new Paragraph("Publish the mood, share the technology and turn around the messy news.", textFont)); section = section2.addSection(new Paragraph(new Chunk("twitter", secFont))); section.setIndentation(10); section.setIndentationLeft(10); section.setBookmarkOpen(false); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); section.add(new Paragraph(new Chunk("twitter: @suncto", textFont) .setUnderline(0.2f, -2f).setAnchor("twitter: twitter: twitter: "))); section.add(new Paragraph("A place often walled", textFont)); LineSeparator line = new LineSeparator(1, 100, new BaseColor(204, 204, 204), Element.ALIGN_CENTER, -2); Paragraph p_line = new Paragraph("Split line"); p_line.add(line); chapter.add(p_line); document.add(chapter); chapter = new Chapter(new Paragraph("Miu Introduction of", chFont), chNum++); section = chapter.addSection(new Paragraph("essential information", secFont)); section.setIndentation(10); section.setIndentationLeft(10); section.setBookmarkOpen(false); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); section.add(new Paragraph("90 The latter one likes food and Tourism...", textFont)); document.add(chapter); document.close();
3. IText create PDF
import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Date; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class PDFJiemi { private static String USER_PASS = "Hello123"; private static String OWNER_PASS = "Owner123"; public static void main(String[] args) { try { OutputStream file = new FileOutputStream(new File("E:\\pdfile\\NeedToDo\\Jiemi\\Test2.pdf")); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, file); writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); document.open(); document.add(new Paragraph("Hello World, iText")); document.add(new Paragraph(new Date().toString())); document.close(); file.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("OK."); } }
4. Attach PDFBox to judge whether the PDF document is encrypted
import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; public class PDFIsEncrypted { public static void main(String[] args) throws IOException { PDDocument pdf = PDDocument.load(new File("E:\\pdfile\\NeedToDo\\Jiemi\\addWaterTest.pdf")); System.out.println("isEncrypted : " + pdf.isEncrypted()); } }
5. IText cracking encrypted PDF documents
import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfWriter; public class DeEncrypt { public static void main(String[] args) throws Exception { String srcFile = "E:\\pdfile\\NeedToDo\\Jiemi\\addWaterTest.pdf"; String dstFile = "E:\\pdfile\\NeedToDo\\Jiemi\\DeEncryption.pdf"; deletePDFEncrypt(srcFile, dstFile); System.out.println("OK."); } private static void deletePDFEncrypt(String sourceFullName, String newFullName) throws Exception { if (sourceFullName == null || sourceFullName.isEmpty() || sourceFullName.length() == 0) { throw new Exception("Source file path is empty or null."); } try { // Create a pdfleader object PdfReader reader = new PdfReader(sourceFullName); PdfReader.unethicalreading = true; // Gets the size of the first page Rectangle pagesize = reader.getPageSize(1); float width = pagesize.getWidth(); float height = pagesize.getHeight(); // Create a document variable OutputStream file = new FileOutputStream(new File(newFullName)); Document document = new Document(pagesize, 50, 50, 50, 50); // Create this document PdfWriter writer = PdfWriter.getInstance(document, file); // open documents document.open(); // Add content PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < reader.getNumberOfPages()) { pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(reader, pageOfCurrentReaderPDF); document.setPageSize(new Rectangle(page.getWidth(), page.getHeight())); document.newPage(); cb.addTemplate(page, 0, 0); } // close document document.close(); } catch (Exception ex) { ex.printStackTrace(); } } }