Exemplo n.º 1
0
		/*
		private static Document[] RefreshAndFill(string command) {
			//No need to check RemotingRole; no call to db.
			return Fill(Db.GetTable(command));
		}*/

		///<summary>Usually, set just the extension before passing in the doc.  Inserts a new document into db, creates a filename based on Cur.DocNum, and then updates the db with this filename.  Should always refresh the document after calling this method in order to get the correct filename for RemotingRole.ClientWeb.</summary>
		public static long Insert(Document doc,Patient pat) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				doc.DocNum=Meth.GetLong(MethodBase.GetCurrentMethod(),doc,pat);
				return doc.DocNum;
			}
			doc.DocNum=Crud.DocumentCrud.Insert(doc);
			//If the current filename is just an extension, then assign it a unique name.
			if(doc.FileName==Path.GetExtension(doc.FileName)) {
				string extension=doc.FileName;
				doc.FileName="";
				string s=pat.LName+pat.FName;
				for(int i=0;i<s.Length;i++) {
					if(Char.IsLetter(s,i)) {
						doc.FileName+=s.Substring(i,1);
					}
				}
				doc.FileName+=doc.DocNum.ToString()+extension;//ensures unique name
				//there is still a slight chance that someone manually added a file with this name, so quick fix:
				string command="SELECT FileName FROM document WHERE PatNum="+POut.Long(doc.PatNum);
				DataTable table=Db.GetTable(command);
				string[] usedNames=new string[table.Rows.Count];
				for(int i=0;i<table.Rows.Count;i++) {
					usedNames[i]=PIn.String(table.Rows[i][0].ToString());
				}
				while(IsFileNameInList(doc.FileName,usedNames)) {
					doc.FileName="x"+doc.FileName;
				}
				/*Document[] docList=GetAllWithPat(doc.PatNum);
				while(IsFileNameInList(doc.FileName,docList)) {
					doc.FileName="x"+doc.FileName;
				}*/
				Update(doc);
			}
			return doc.DocNum;
		}
Exemplo n.º 2
0
Arquivo: Printing.cs Projeto: mnisl/OD
        public override void OnEndPrint(PrintDocument document, PrintEventArgs e)
        {
            base.OnEndPrint(document, e);
            document.PrinterSettings.PrintToFile = _isPrintToFile;

            if (ShowAfterPrint)
                System.Diagnostics.Process.Start(this.FileName);

            Document doc = new Document();
            doc.DateCreated = File.GetLastWriteTime(this.FileName);
            if (_sit == PrintSituation.Claim)
            {
                doc.DocCategory = DefC.GetByExactName(DefCat.ImageCats, "EClaims");
                if (doc.DocCategory == 0)
                {
                    Def d = new Def() { Category = DefCat.ImageCats, ItemName = "EClaims" };
                    doc.DocCategory = Defs.Insert(d);
                    DataValid.SetInvalid(InvalidType.Defs);
                }
            }
            else
            {
                doc.DocCategory = DefC.GetList(DefCat.ImageCats)[0].DefNum;//First category.
            }
            doc.FileName = Path.GetFileName(this.FileName);
            doc.Description = doc.FileName;
            doc.PatNum = _patient.PatNum;
            Documents.Insert(doc);
        }
Exemplo n.º 3
0
 ///<summary></summary>
 public static void Delete(Document doc)
 {
     if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
         Meth.GetVoid(MethodBase.GetCurrentMethod(),doc);
         return;
     }
     string command= "DELETE from document WHERE DocNum = '"+doc.DocNum.ToString()+"'";
     Db.NonQ(command);
     DeletedObjects.SetDeleted(DeletedObjectType.Document,doc.DocNum);
 }
Exemplo n.º 4
0
		///<summary>Takes in a mount object and finds all the images pertaining to the mount, then concatonates them together into one large, unscaled image and returns that image. Set imageSelected=-1 to unselect all images, or set to an image ordinal to highlight the image. The mount is rendered onto the given mountImage, so it must have been appropriately created by CreateBlankMountImage(). One can create a mount template by passing in arrays of zero length.</summary>
		public static void RenderMountImage(Bitmap mountImage, Bitmap[] originalImages, List <MountItem> mountItems, Document[] documents, int imageSelected) {
			using (Graphics g = Graphics.FromImage(mountImage)) {
				//Draw mount encapsulating background rectangle.
				g.Clear(Pens.SlateGray.Color);
				RenderMountFrames(mountImage, mountItems, imageSelected);
				for (int i = 0; i < mountItems.Count; i++) {
					g.FillRectangle(Brushes.Black, mountItems[i].Xpos, mountItems[i].Ypos,
						mountItems[i].Width, mountItems[i].Height);//draw box behind image
					RenderImageIntoMount(mountImage, mountItems[i], originalImages[i], documents[i]);
				}
			}
		}
Exemplo n.º 5
0
		///<summary>Renders the given image using the settings provided by the given document object into the location of the given mountItem object.</summary>
		public static void RenderImageIntoMount(Bitmap mountImage, MountItem mountItem, Bitmap mountItemImage, Document mountItemDoc) {
			if (mountItem == null) {
				return;
			}
			using(Graphics g = Graphics.FromImage(mountImage)) {
				g.FillRectangle(Brushes.Black, mountItem.Xpos, mountItem.Ypos, mountItem.Width, mountItem.Height);//draw box behind image
				Bitmap image = ApplyDocumentSettingsToImage(mountItemDoc,mountItemImage,ImageSettingFlags.ALL);
				if (image == null) {
					return;
				}
				float widthScale = ((float)mountItem.Width) / image.Width;
				float heightScale = ((float)mountItem.Height) / image.Height;
				float scale = (widthScale < heightScale ? widthScale : heightScale);
				RectangleF imageRect = new RectangleF(0, 0, scale * image.Width, scale * image.Height);
				imageRect.X = mountItem.Xpos + mountItem.Width / 2 - imageRect.Width / 2;
				imageRect.Y = mountItem.Ypos + mountItem.Height / 2 - imageRect.Height / 2;
				g.DrawImage(image, imageRect);
				image.Dispose();
			}
		}
Exemplo n.º 6
0
        ///<summary>Uses sheet framework to generate a PDF file, save it to patient's image folder, and attempt to launch file with defualt reader.
        ///If using ImagesStoredInDB it will not launch PDF. If no valid patient is selected you cannot perform this action.</summary>
        private void butPDF_Click(object sender, EventArgs e)
        {
            if (PatCur == null)           //not attached to a patient when form loaded and they haven't selected a patient to attach to yet
            {
                MsgBox.Show(this, "The Medical Lab must be attached to a patient before the PDF can be saved.");
                return;
            }
            if (PatCur.PatNum > 0 && _medLabCur.PatNum != PatCur.PatNum)         //save the current patient attached to the MedLab if it has been changed
            {
                MoveLabsAndImagesHelper();
            }
            Cursor = Cursors.WaitCursor;
            SheetDef sheetDef = SheetUtil.GetMedLabResultsSheetDef();
            Sheet    sheet    = SheetUtil.CreateSheet(sheetDef, _medLabCur.PatNum);

            SheetFiller.FillFields(sheet, null, null, _medLabCur);
            //create the file in the temp folder location, then import so it works when storing images in the db
            string tempPath = ODFileUtils.CombinePaths(PrefC.GetTempFolderPath(), _medLabCur.PatNum.ToString() + ".pdf");

            SheetPrinting.CreatePdf(sheet, tempPath, null, _medLabCur);
            HL7Def defCur   = HL7Defs.GetOneDeepEnabled(true);
            long   category = defCur.LabResultImageCat;

            if (category == 0)
            {
                category = Defs.GetFirstForCategory(DefCat.ImageCats, true).DefNum;             //put it in the first category.
            }
            //create doc--------------------------------------------------------------------------------------
            OpenDentBusiness.Document docc = null;
            try {
                docc = ImageStore.Import(tempPath, category, Patients.GetPat(_medLabCur.PatNum));
            }
            catch (Exception ex) {
                ex.DoNothing();
                Cursor = Cursors.Default;
                MsgBox.Show(this, "Error saving document.");
                return;
            }
            finally {
                //Delete the temp file since we don't need it anymore.
                try {
                    File.Delete(tempPath);
                }
                catch {
                    //Do nothing.  This file will likely get cleaned up later.
                }
            }
            docc.Description = Lan.g(this, "MedLab Result");
            docc.DateCreated = DateTime.Now;
            Documents.Update(docc);
            string filePathAndName = "";

            if (PrefC.AtoZfolderUsed == DataStorageType.LocalAtoZ)
            {
                string patFolder = ImageStore.GetPatientFolder(Patients.GetPat(_medLabCur.PatNum), ImageStore.GetPreferredAtoZpath());
                filePathAndName = ODFileUtils.CombinePaths(patFolder, docc.FileName);
            }
            else if (CloudStorage.IsCloudStorage)
            {
                FormProgress FormP = new FormProgress();
                FormP.DisplayText          = "Downloading...";
                FormP.NumberFormat         = "F";
                FormP.NumberMultiplication = 1;
                FormP.MaxVal = 100;              //Doesn't matter what this value is as long as it is greater than 0
                FormP.TickMS = 1000;
                OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(
                    ImageStore.GetPatientFolder(Patients.GetPat(_medLabCur.PatNum), ImageStore.GetPreferredAtoZpath())
                    , docc.FileName
                    , new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
                if (FormP.ShowDialog() == DialogResult.Cancel)
                {
                    state.DoCancel = true;
                    return;
                }
                filePathAndName = PrefC.GetRandomTempFile(Path.GetExtension(docc.FileName));
                File.WriteAllBytes(filePathAndName, state.FileContent);
            }
            Cursor = Cursors.Default;
            if (filePathAndName != "")
            {
                Process.Start(filePathAndName);
            }
            SecurityLogs.MakeLogEntry(Permissions.SheetEdit, sheet.PatNum, sheet.Description + " from " + sheet.DateTimeSheet.ToShortDateString() + " pdf was created");
            DialogResult = DialogResult.OK;
        }
Exemplo n.º 7
0
		///<summary></summary>
		public static void Update(Document doc){
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				Meth.GetVoid(MethodBase.GetCurrentMethod(),doc);
				return;
			}
			Crud.DocumentCrud.Update(doc);
		}
Exemplo n.º 8
0
		///<summary>This is a generic insert statement used to insert documents with custom file names.</summary>
		public static long Insert(Document doc) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetLong(MethodBase.GetCurrentMethod(),doc);
			}
			return Crud.DocumentCrud.Insert(doc);
		}
Exemplo n.º 9
0
		///<summary>Any filenames mentioned in the fileList which are not attached to the given patient are properly attached to that patient. Returns the total number of documents that were newly attached to the patient.</summary>
		public static int InsertMissing(Patient patient,List<string> fileList) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetInt(MethodBase.GetCurrentMethod(),patient,fileList);
			}
			int countAdded=0;
			string command="SELECT FileName FROM document WHERE PatNum='"+patient.PatNum+"' ORDER BY FileName";
			DataTable table=Db.GetTable(command);
			for(int j=0;j<fileList.Count;j++){
				string fileName=Path.GetFileName(fileList[j]);
				if(!IsAcceptableFileName(fileName)){
					continue;
				}
				bool inList=false;
				for(int i=0;i<table.Rows.Count && !inList;i++){
					inList=(table.Rows[i]["FileName"].ToString()==fileName);
				}
				if(!inList){//OD found new images in the patient's folder that aren't part of the DB.
					Document doc=new Document();
					doc.DateCreated=File.GetLastWriteTime(fileList[j]);
					doc.Description=fileName;
					doc.DocCategory=DefC.GetList(DefCat.ImageCats)[0].DefNum;//First category.
					doc.FileName=fileName;
					doc.PatNum=patient.PatNum;
					Insert(doc,patient);
					countAdded++;
					string docCat=DefC.GetDef(DefCat.ImageCats,doc.DocCategory).ItemName;
					SecurityLogs.MakeLogEntry(Permissions.ImageEdit,patient.PatNum,Lans.g("ContrImages","Document Created: A file")+", "+doc.FileName+", "+Lans.g("ContrImages","placed into the patient's AtoZ images folder from outside of the program was detected and a record automatically inserted into the first image category")+", "+docCat,doc.DocNum);
				}
			}
			return countAdded;
		}
Exemplo n.º 10
0
		///<summary>Returns the documents which correspond to the given mountitems.</summary>
		public static Document[] GetDocumentsForMountItems(List <MountItem> mountItems) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetObject<Document[]>(MethodBase.GetCurrentMethod(),mountItems);
			}
			if(mountItems==null || mountItems.Count<1){
				return new Document[0];
			}
			Document[] documents=new Document[mountItems.Count];
			for(int i=0;i<mountItems.Count;i++){
				string command="SELECT * FROM document WHERE MountItemNum='"+POut.Long(mountItems[i].MountItemNum)+"'";
				DataTable table=Db.GetTable(command);
				if(table.Rows.Count<1){
					documents[i]=null;
				}else{
					documents[i]=Fill(table)[0];
				}
			}
			return documents;
		}
Exemplo n.º 11
0
		///<summary>Gets the corresponding thumbnail image for the given document object. The document is expected to be an image, and a 'not available' image is returned if the document is not an image. The thumbnail for every document is in a folder named 'thumbnails' within the same directly level.</summary>
		public static Bitmap GetThumbnail(Document doc,string patFolder,int size){
			//No need to check RemotingRole; no call to db.
			string shortFileName=doc.FileName;
			//If no file name associated with the document, then there cannot be a thumbnail,
			//because thumbnails have the same name as the original image document.
			if(shortFileName.Length<1) {
				return NoAvailablePhoto(size);
			}
			string fullName=ODFileUtils.CombinePaths(patFolder,shortFileName);
			//If the document no longer exists, then there is no corresponding thumbnail image.
			if(!File.Exists(fullName)) {
				return NoAvailablePhoto(size);
			}
			//If the specified document is not an image return 'not available'.
			if(!ImageHelper.HasImageExtension(fullName)) {
				return NoAvailablePhoto(size);
			}
			//Create Thumbnails folder if it does not already exist for this patient folder.
			string thumbPath=ODFileUtils.CombinePaths(patFolder,"Thumbnails");
			if(!Directory.Exists(thumbPath)) {
				try {
					Directory.CreateDirectory(thumbPath);
				} 
				catch {
					throw new ApplicationException(Lans.g("Documents","Error: Could not create 'Thumbnails' folder for patient: ")+thumbPath);
				}
			}
			string thumbFileExt=Path.GetExtension(shortFileName);
			string thumbCoreFileName=shortFileName.Substring(0,shortFileName.Length-thumbFileExt.Length);
			string thumbFileName=ODFileUtils.CombinePaths(new string[] { patFolder,"Thumbnails",
				thumbCoreFileName+"_"+size+thumbFileExt} );
			//Use the existing thumbnail if it already exists and it was created after the last document modification.
			if(File.Exists(thumbFileName)) {
				DateTime thumbModifiedTime=File.GetLastWriteTime(thumbFileName);
				if(thumbModifiedTime>doc.DateTStamp){
					return (Bitmap)Bitmap.FromFile(thumbFileName);
				}
			}
			//Add thumbnail
			Bitmap thumbBitmap;
			//Gets the cropped/flipped/rotated image with any color filtering applied.
			Bitmap sourceImage=new Bitmap(fullName);
			Bitmap fullImage=ImageHelper.ApplyDocumentSettingsToImage(doc,sourceImage,ImageSettingFlags.ALL);
			sourceImage.Dispose();
			thumbBitmap=ImageHelper.GetThumbnail(fullImage,size);
			fullImage.Dispose();
			try {
				thumbBitmap.Save(thumbFileName);
			} catch {
				//Oh well, we can regenerate it next time if we have to!
			}
			return thumbBitmap;
		}
Exemplo n.º 12
0
		///<summary></summary>
		public static bool Update(Document doc,Document docOld){
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetBool(MethodBase.GetCurrentMethod(),doc,docOld);
			}
			return Crud.DocumentCrud.Update(doc,docOld);
		}
Exemplo n.º 13
0
		///<summary>Applies the document specified cropping, flip, rotation, brightness and contrast transformations to the image and returns the resulting image. Zoom and translation must be handled by the calling code. The returned image is always a new image that can be modified without affecting the original image. The change in the image's center point is returned into deltaCenter, so that rotation offsets can be properly calculated when displaying the returned image.</summary>
		public static Bitmap ApplyDocumentSettingsToImage(Document doc, Bitmap image, ImageSettingFlags settings) {
			if(image==null) {//Any operation on a non-existant image produces a non-existant image.
				return null;
			}
			if(doc==null) {//No doc implies no operations, implies that the image should be returned "unaltered".
				//return (Bitmap)image.Clone();//this would keep the original resolution, which causes problems.
				return new Bitmap(image);//resets the resolution to 96, just like it does for docs 20 lines down.
			}
			//CROP - Implies that the croping rectangle must be saved in raw-image-space coordinates, 
			//with an origin of that equal to the upper left hand portion of the image.
			Rectangle cropResult;
			if((settings & ImageSettingFlags.CROP) != 0 &&	//Crop not requested.
				doc.CropW > 0 && doc.CropH > 0)//No clip area yet defined, so no clipping is performed.
			{
				float[] cropDims = ODMathLib.IntersectRectangles(0, 0, image.Width, image.Height,//Intersect image rectangle with
					doc.CropX, doc.CropY, doc.CropW, doc.CropH);//document crop rectangle.
				if (cropDims.Length == 0) {//The entire image has been cropped away.
					return null;
				}
				//Rounds dims up, so that data is not lost, but possibly not removing all of what was expected.
				cropResult = new Rectangle((int)cropDims[0], (int)cropDims[1],
					(int)Math.Ceiling(cropDims[2]), (int)Math.Ceiling(cropDims[3]));
			}
			else {
				cropResult = new Rectangle(0, 0, image.Width, image.Height);//No cropping.
			}
			//Always use 32-bit images in memory. We could use 24-bit images here (it works in Windows, but MONO produces
			//output using 32-bit data on a 24-bit image in that case, providing horrible output). Perhaps we can update
			//this when MONO is more fully featured.
			Bitmap cropped = new Bitmap(cropResult.Width, cropResult.Height, PixelFormat.Format32bppArgb);
			Graphics g = Graphics.FromImage(cropped);
			Rectangle croppedDims = new Rectangle(0, 0, cropped.Width, cropped.Height);
			g.DrawImage(image, croppedDims, cropResult, GraphicsUnit.Pixel);
			g.Dispose();
			//FLIP AND ROTATE - must match the operations in GetDocumentFlippedRotatedMatrix().
			if((settings & ImageSettingFlags.FLIP) != 0) {
				if (doc.IsFlipped) {
					cropped.RotateFlip(RotateFlipType.RotateNoneFlipX);
				}
			}
			if((settings & ImageSettingFlags.ROTATE) != 0) {
				if (doc.DegreesRotated % 360 == 90) {
					cropped.RotateFlip(RotateFlipType.Rotate90FlipNone);
				}
				else if (doc.DegreesRotated % 360 == 180) {
					cropped.RotateFlip(RotateFlipType.Rotate180FlipNone);
				}
				else if (doc.DegreesRotated % 360 == 270) {
					cropped.RotateFlip(RotateFlipType.Rotate270FlipNone);
				}
			}
			//APPLY BRIGHTNESS AND CONTRAST - 
			//TODO: should be updated later for more general functions 
			//(create inputValues and outputValues from stored db function/table).
			if((settings & ImageSettingFlags.COLORFUNCTION) != 0 &&
				doc.WindowingMax != 0 && //Do not apply color function if brightness/contrast have never been set (assume normal settings).
				!(doc.WindowingMax == 255 && doc.WindowingMin == 0)) {//Don't apply if brightness/contrast settings are normal.
				float[] inputValues = new float[] {
					doc.WindowingMin/255f,
					doc.WindowingMax/255f,
				};
				float[] outputValues = new float[]{
					0,
					1,
				};
				BitmapData croppedData = null;
				try {
					croppedData = cropped.LockBits(new Rectangle(0, 0, cropped.Width, cropped.Height),
						ImageLockMode.ReadWrite, cropped.PixelFormat);
					unsafe {
						byte* pBits;
						if (croppedData.Stride < 0) {
							pBits = (byte*)croppedData.Scan0.ToPointer() + croppedData.Stride * (croppedData.Height - 1);
						}
						else {
							pBits = (byte*)croppedData.Scan0.ToPointer();
						}
						//The following loop goes through each byte of each 32-bit value and applies the color function to it.
						//Thus, the same transformation is performed to all 4 color components equivalently for each pixel.
						for (int i = 0; i < croppedData.Stride * croppedData.Height; i++) {
							float colorComponent = pBits[i] / 255f;
							float rangedOutput;
							if (colorComponent <= inputValues[0]) {
								rangedOutput = outputValues[0];
							}
							else if (colorComponent >= inputValues[inputValues.Length - 1]) {
								rangedOutput = outputValues[outputValues.Length - 1];
							}
							else {
								int j = 0;
								while (!(inputValues[j] <= colorComponent && colorComponent < inputValues[j + 1])) {
									j++;
								}
								rangedOutput = ((colorComponent - inputValues[j]) * (outputValues[j + 1] - outputValues[j]))
									/ (inputValues[j + 1] - inputValues[j]);
							}
							pBits[i] = (byte)Math.Round(255 * rangedOutput);
						}
					}
				}
				catch {
				}
				finally {
					try {
						cropped.UnlockBits(croppedData);
					}
					catch {
					}
				}
			}
			return cropped;
		}
Exemplo n.º 14
0
 ///<summary>Any filenames mentioned in the fileList which are not attached to the given patient are properly attached to that patient. Returns the total number of documents that were newly attached to the patient.</summary>
 public static int InsertMissing(Patient patient,List<string> fileList)
 {
     if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
         return Meth.GetInt(MethodBase.GetCurrentMethod(),patient,fileList);
     }
     int countAdded=0;
     string command="SELECT FileName FROM document WHERE PatNum='"+patient.PatNum+"' ORDER BY FileName";
     DataTable table=Db.GetTable(command);
     for(int j=0;j<fileList.Count;j++){
         string fileName=Path.GetFileName(fileList[j]);
         if(!IsAcceptableFileName(fileName)){
             continue;
         }
         bool inList=false;
         for(int i=0;i<table.Rows.Count && !inList;i++){
             inList=(table.Rows[i]["FileName"].ToString()==fileName);
         }
         if(!inList){
             Document doc=new Document();
             doc.DateCreated=File.GetLastWriteTime(fileList[j]);
             doc.Description=fileName;
             doc.DocCategory=DefC.GetList(DefCat.ImageCats)[0].DefNum;//First category.
             doc.FileName=fileName;
             doc.PatNum=patient.PatNum;
             Insert(doc,patient);
             countAdded++;
         }
     }
     return countAdded;
 }
Exemplo n.º 15
0
		private void ToolBarMainPrint_Click() {
			if(PrefC.GetBool(PrefName.FuchsOptionsOn)) {
				if(checkShowDiscount.Checked || checkShowIns.Checked) {
					if(MessageBox.Show(this,string.Format(Lan.g(this,"Do you want to remove insurance estimates and discounts from printed treatment plan?")),"Open Dental",MessageBoxButtons.YesNo,MessageBoxIcon.Question) != DialogResult.No) {
						checkShowDiscount.Checked=false;
						checkShowIns.Checked=false;
						FillMain();
					}
				}
			}
			PrepImageForPrinting();
			MigraDoc.DocumentObjectModel.Document doc=CreateDocument();
			MigraDoc.Rendering.Printing.MigraDocPrintDocument printdoc=new MigraDoc.Rendering.Printing.MigraDocPrintDocument();
			MigraDoc.Rendering.DocumentRenderer renderer=new MigraDoc.Rendering.DocumentRenderer(doc);
			renderer.PrepareDocument();
			printdoc.Renderer=renderer;
			//we might want to surround some of this with a try-catch
			#if DEBUG
				pView = new FormRpPrintPreview();
				pView.printPreviewControl2.Document=printdoc;
				pView.ShowDialog();			
			#else
				if(PrinterL.SetPrinter(pd2,PrintSituation.TPPerio,PatCur.PatNum,"Treatment plan for printed")){
					printdoc.PrinterSettings=pd2.PrinterSettings;
					printdoc.Print();
				}
			#endif
			long category=0;
			OpenDentBusiness.Document docSave = new OpenDentBusiness.Document();
			MigraDoc.Rendering.PdfDocumentRenderer pdfRenderer = new MigraDoc.Rendering.PdfDocumentRenderer(false,PdfFontEmbedding.Always);
			pdfRenderer.Document=CreateDocument();
			pdfRenderer.RenderDocument();
			//Check if there are any image category definitions with "TreatPlans"
			for(int i=0;i<DefC.Short[(int)DefCat.ImageCats].Length;i++) {
				if((DefC.Short[(int)DefCat.ImageCats][i].ItemValue=="R" || DefC.Short[(int)DefCat.ImageCats][i].ItemValue=="XR") && PrefC.AtoZfolderUsed) {
					long docNum=Documents.Insert(docSave);
					category=DefC.Short[(int)DefCat.ImageCats][i].DefNum;
					string filePath=ImageStore.GetPatientFolder(PatCur,ImageStore.GetPreferredAtoZpath());
					string fileName="TPArchive"+docSave.DocNum;
					//Then create a PDF and save it to the AtoZ folder if AtoZ pref is on.
					byte[] rawData= { };
					if(PrefC.AtoZfolderUsed) {
						if(filePath.EndsWith("\\")) {
						}
						else {
							filePath+="\\";
						}
						pdfRenderer.Save(filePath+fileName+".pdf");
					}
					//Currently never going to get hit because of AtoZ folder check above. This is due to AxAcroPDF functionality.
					else {//saving to db
						using(MemoryStream stream=new MemoryStream()) {
							pdfRenderer.Save(stream,false);
							rawData=stream.ToArray();
							stream.Close();
						}
					}
					docSave.ImgType=ImageType.Document;
					docSave.DateCreated=DateTime.Today;
					docSave.PatNum=PatCur.PatNum;
					docSave.DocCategory=category;
					docSave.Description=fileName;
					if(!PrefC.AtoZfolderUsed) {
						docSave.RawBase64=Convert.ToBase64String(rawData);
					}
					else {
						docSave.FileName=fileName+".pdf";
					}
					Documents.Update(docSave);//creates filename and saves to db
				}
			}
		}