【Java】PDFからJPG変換

PDFファイルに利用されている画像をJPG変換します。
以下のライブラリが必要です。
pdfbox-2.0.7.jar
commons-logging-1.2.jar

1import java.io.File;
2import java.io.FileOutputStream;
3import java.io.IOException;
4import java.util.Iterator;
5 
6import javax.imageio.ImageIO;
7 
8import org.apache.pdfbox.cos.COSName;
9import org.apache.pdfbox.pdmodel.PDDocument;
10import org.apache.pdfbox.pdmodel.PDPage;
11import org.apache.pdfbox.pdmodel.PDPageTree;
12import org.apache.pdfbox.pdmodel.PDResources;
13import org.apache.pdfbox.pdmodel.graphics.PDXObject;
14import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
15 
16public class TestPDFBoxPdfToJpg {
17 
18    public static void main(String[] args) {
19        //PDFドキュメントをロード
20        try (PDDocument document = PDDocument.load(new File("D:\\test\\pdf\\e-ticket.pdf"));) {
21 
22            //ページのリストから最初の1ページを取得する
23            PDPageTree pageTree = document.getDocumentCatalog().getPages();
24            PDPage page = pageTree.get(0);
25 
26            //ページからリソースを取得し、最初のイメージを取得する。
27            PDResources resources = page.getResources();
28            Iterator<COSName> ite = resources.getXObjectNames().iterator();
29 
30            int i = 0;
31 
32            while (ite.hasNext()) {
33 
34                COSName name = ite.next();
35 
36                //取得したイメージをファイルに出力
37                PDXObject xobject = resources.getXObject(name);
38 
39                if (xobject instanceof PDImageXObject) {
40                    PDImageXObject image2 = (PDImageXObject) resources.getXObject(name);
41                    ImageIO.write(image2.getImage(), "jpg", new FileOutputStream("D:\\test\\pdf\\e-ticket" + i + ".jpg"));
42                }
43 
44                i++;
45            }
46 
47        } catch (IOException e) {
48            e.printStackTrace();
49        }
50    }
51}

【Excel】圧縮解凍処理

VBAで圧縮解凍処理を行います。

1'オプションの意味:変数宣言必須
2Option Explicit
3 
4'圧縮処理(実行)
5Public Sub ZipSample()
6  ZipFileOrFolder "C:\Test\Files" 'フォルダ圧縮
7  MsgBox "処理が終了しました。", vbInformation + vbSystemModal
8End Sub
9 
10'解凍処理(実行)
11Public Sub UnZipSample()
12  UnZipFile "C:\Test\Files\Test.zip"
13  MsgBox "処理が終了しました。", vbInformation + vbSystemModal
14End Sub
15 
16'圧縮処理
17Public Sub ZipFileOrFolder(ByVal SrcPath As Variant, _
18                           Optional ByVal DestFolderPath As Variant = "")
19  'ファイル・フォルダをZIP形式で圧縮
20  'SrcPath:元ファイル・フォルダ
21  'DestFolderPath:出力先、指定しない場合は元ファイル・フォルダと同じ場所
22  Dim DestFilePath As Variant
23 
24  With CreateObject("Scripting.FileSystemObject")
25    If IsFolder(DestFolderPath) = False Then
26      If IsFolder(SrcPath) = True Then
27        DestFolderPath = SrcPath
28      ElseIf IsFile(SrcPath) = True Then
29        DestFolderPath = .GetFile(SrcPath).ParentFolder.Path
30      Else: Exit Sub
31      End If
32    End If
33    DestFilePath = AddPathSeparator(DestFolderPath) & _
34                     .GetBaseName(SrcPath) & ".zip"
35    '空のZIPファイル作成
36    With .CreateTextFile(DestFilePath, True)
37      .Write ChrW(&H50) & ChrW(&H4B) & ChrW(&H5) & ChrW(&H6) & String(18, ChrW(0))
38      .Close
39    End With
40  End With
41    
42  With CreateObject("Shell.Application")
43    With .NameSpace(DestFilePath)
44      .CopyHere SrcPath
45      While .Items.Count < 1
46        DoEvents
47      Wend
48    End With
49  End With
50End Sub
51 
52'解凍処理
53Public Sub UnZipFile(ByVal SrcPath As Variant, _
54                     Optional ByVal DestFolderPath As Variant = "")
55  'ZIPファイルを解凍
56  'SrcPath:元ファイル
57  'DestFolderPath:出力先、指定しない場合は元ファイルと同じ場所
58  '※出力先に同名ファイルがあった場合はユーザー判断で処理
59  With CreateObject("Scripting.FileSystemObject")
60    If .FileExists(SrcPath) = False Then Exit Sub
61    If LCase(.GetExtensionName(SrcPath)) <> "zip" Then Exit Sub
62    If IsFolder(DestFolderPath) = False Then
63      DestFolderPath = .GetFile(SrcPath).ParentFolder.Path
64    End If
65  End With
66    
67  With CreateObject("Shell.Application")
68    .NameSpace(DestFolderPath).CopyHere .NameSpace(SrcPath).Items
69  End With
70End Sub
71 
72'フォルダチェック処理
73Private Function IsFolder(ByVal SrcPath As String) As Boolean
74  IsFolder = CreateObject("Scripting.FileSystemObject").FolderExists(SrcPath)
75End Function
76 
77'ファイルチェック処理
78Private Function IsFile(ByVal SrcPath As String) As Boolean
79  IsFile = CreateObject("Scripting.FileSystemObject").FileExists(SrcPath)
80End Function
81 
82'ファイルパスセパレータ追加処理
83Private Function AddPathSeparator(ByVal SrcPath As String) As String
84  If Right(SrcPath, 1) <> ChrW(92) Then SrcPath = SrcPath & ChrW(92)
85  AddPathSeparator = SrcPath
86End Function

【Excel】ライブラリ参照

Excelでオブジェクトを変数宣言するには
遅延バインディングと事前バインディングの2種類の方法がある。

実装の違い(例として、FileSystemObjectを利用)

  • 事前バインディング
  • 「ツール」→「参照設定」で
    「Microsoft Scripting Runtime」にチェックを付ける。

    1Dim objFSO As New FileSystemObject
    2または、
    3Dim objFSO As FileSystemObject
    4Set objFSO = New FileSystemObject

一言で言えば、変数宣言の型が
遅延バインディングはObject型
事前バインディングは特定のオブジェクト型
となっている。

  • 遅延バインディング(実行時バインディング)
  • オブジェクトが Object 型として宣言された変数に代入する場合、
    遅延(実行時)にバインディングされる。
    この型のオブジェクトは、任意のオブジェクトへの参照を保持できるが、
    事前バインディングされたオブジェクトの利点をほとんど持たない。

  • 事前バインディング
  • 特定のオブジェクト型として宣言された変数に代入する場合、
    オブジェクトは事前(コンパイル時に)バインディングされる。
    事前バインディングされたオブジェクトでは、アプリケーションが実行される前に、
    コンパイラによってメモリの割り当てとその他の最適化が実行される。
    また、自動クイックヒントが表示されるようになる。

    【Excel】名前の定義削除

    名前の定義は有能だと思うのですが、
    参考ブックからコピーすると一緒にコピーされ、
    収集つかなくなるためこれで削除します。

    1Option Explicit
    2 
    3Private Sub NameDefDel()
    4    Dim Ans, RefStyle, n
    5     
    6    Ans = MsgBox("実行しますか?", vbYesNo, "実行確認")
    7    If Ans = vbNo Then Exit Sub
    8     
    9    RefStyle = Application.ReferenceStyle
    10     
    11    If RefStyle = xlR1C1 Then
    12        Application.ReferenceStyle = xlA1
    13    Else
    14        Application.ReferenceStyle = xlR1C1
    15    End If
    16 
    17    For Each n In ActiveWorkbook.Names
    18        If Not n.Name Like "*!Print_Area" And _
    19            Not n.Name Like "*!Print_Titles" Then
    20            n.Delete
    21        End If
    22    Next
    23 
    24    Application.ReferenceStyle = RefStyle
    25     
    26    MsgBox "完了しました!"
    27End Sub

    【Java】例外内容を文字列で取得する

    例外内容を文字列で取得します。
    例外内容をメール本文等に出力する際に利用します。

    1/**
    2 * 例外内容取得処理
    3 * @param 例外オブジェクト
    4 * @return 例外内容文字列
    5 */
    6public static String getTrace(Throwable th) {
    7 
    8    StringBuilder sb = new StringBuilder();
    9    String lineSeparator = System.getProperty("line.separator");
    10 
    11    if (th != null) {
    12        sb.append(th.getClass().getName() + ":" + th.getMessage());
    13        StackTraceElement[] stack = th.getStackTrace();
    14        if (stack != null) {
    15            for (int i = 0; i < stack.length; i++) {
    16                sb.append(lineSeparator);
    17                sb.append("\tat " + stack[i].toString());
    18            }
    19        }
    20        sb.append(lineSeparator);
    21 
    22        Throwable causeTh = th.getCause();
    23        String caused = getCaused(causeTh);
    24        sb.append(caused);
    25    }
    26 
    27    return sb.toString();
    28}
    29 
    30/**
    31 * 例外内容取得処理(原因)
    32 * @param 例外オブジェクト
    33 * @return 例外内容文字列
    34 */
    35public static String getCaused(Throwable th) {
    36 
    37    StringBuilder sb = new StringBuilder();
    38    String lineSeparator = System.getProperty("line.separator");
    39    Throwable chainTh = null;
    40 
    41    if (th != null) {
    42        sb.append("Caused by: " + th.getClass().getName() + ":" + th.getMessage());
    43        StackTraceElement[] stack = th.getStackTrace();
    44        if (stack != null) {
    45            for (int i = 0; i < stack.length; i++) {
    46                sb.append(lineSeparator);
    47                sb.append("\tat " + stack[i].toString());
    48            }
    49        }
    50        sb.append(lineSeparator);
    51 
    52        chainTh = th.getCause();
    53 
    54    } else {
    55        return sb.toString();
    56    }
    57 
    58    return sb.append(getCaused(chainTh)).toString();
    59}
    60 
    61/**
    62 * テストドライバ
    63 * @param args
    64 */
    65public static void main(String[] args) {
    66 
    67    try {
    68        test();
    69    } catch (Throwable th) {
    70        System.out.println("JavaAPIで例外出力");
    71        th.printStackTrace();
    72 
    73        System.out.println();
    74        System.out.println("独自APIで例外出力");
    75        System.out.println(getTrace(th));
    76    }
    77}
    78public static void test() throws Exception {
    79    try {
    80        try {
    81            int i = 0;
    82            int j = 100;
    83            int k = j/i; // ここでエラー発生
    84        } catch (Exception e) {
    85            throw new Exception("エラー", e);
    86        }
    87    } catch (Exception e) {
    88        //throw e;
    89        throw new Exception("エラー2", e);
    90    }
    91}